python檔案讀寫

來源:互聯網
上載者:User

標籤:python   blog   模式   建立   line   建立檔案   lin   進位   寫入   

1.建立檔案

f=open(filenameWithPath,‘a‘) #建立檔案
f.close()

 

2. 檔案讀取

(1)全部讀取

f=open(檔案絕對路徑,‘r‘)

str=f.readlines()          #讀入全部行的內容,返回字串

 

(2)逐行讀取

f=open(檔案絕對路徑,‘r‘)
line = f.readline()       #逐行讀取,返回字串
while line:
  line = f.readline()
f.close()

3.逐行寫入

f=open(檔案絕對路徑,‘a‘)       #追加模式
f.write(字串 + ‘\n‘)          #逐行寫入,在字串前面或後面加分行符號,不需要逐行寫入時去掉‘\n‘
f.close()

 

4. 檔案open 模式:

w 以寫方式開啟,
a 以追加模式開啟 (從 EOF 開始, 必要時建立新檔案)
r+ 以讀寫入模式開啟
w+ 以讀寫入模式開啟 (參見 w )
a+ 以讀寫入模式開啟 (參見 a )
rb 以二進位讀模式開啟
wb 以二進位寫入模式開啟 (參見 w )
ab 以二進位追加模式開啟 (參見 a )
rb+ 以二進位讀寫入模式開啟 (參見 r+ )
wb+ 以二進位讀寫入模式開啟 (參見 w+ )
ab+ 以二進位讀寫入模式開啟 (參見 a+ )

python檔案讀寫

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.