Python檔案操作

來源:互聯網
上載者:User

標籤:python   檔案   

檔案操作模式

r 唯讀

w 唯寫

a 追加寫

r+ 讀寫

w+ 讀寫,如果檔案已存在則將其刪除,不存在則建立新檔案

a+ 讀寫,如果檔案已存在則在檔案末尾追加,不存在則建立新檔案


熱門檔案操作函數

read() 將檔案內容作為一個大的字串全部讀出來

readline() 讀取檔案中的一行內容

readlines() 將檔案內容作為一個大的列表全部讀出來,每個成員是檔案中的某一行

write() 將字串寫入檔案

writelines(list) 將列表寫入檔案

close() 檔案關閉

tell() 當前遊標的位置

seek(offset[,where])

把檔案指標移動到相對於where的offset位置,where為0表示檔案開始處,這是預設值;1表示當前位置;2表示檔案結尾

flush() 重新整理輸出緩衝,把緩衝區的內容寫入硬碟

truncate([size]) 截取檔案,使檔案大小為size


代碼示範

同一檔案夾下有test.txt檔案和file.py檔案

test.txt檔案內容如下:

aaaaa

bbbbb

ccccc

樣本一:

fp=open(‘test.txt‘,‘r‘)print fp.nameprint fp.modeprint fp.closedfp.close()print fp.closed

>>> 

test.txt

r

False

True

>>> 

執行個體二:

fp=open(‘test.txt‘,‘r‘)print fp.tell()print fp.readline()print fp.tell()fp.seek(0)print fp.readline()print fp.readlines()

>>> 

0

aaaaa


7

aaaaa


[‘bbbbb\n‘, ‘ccccc\n‘]

>>> 

樣本三:

fp=open(‘test1.txt‘,‘w‘)fp.write(‘111\n‘)fp.write(‘222\n‘)fp.writelines([‘111111\n‘,‘222222\n‘])fp.close()

執行之後test1.txt中的內容為:

111

222

111111

222222

樣本四:

fp=open(‘test1.txt‘,‘a‘)fp.truncate(2)fp.close()

執行之後test1.txt中的內容為:

11

樣本五:

fp=open(‘test.txt‘,‘r+‘)print fp.tell()print fp.readlines()print fp.tell()fp.write(‘ddddd\n‘)fp.flush()fp.seek(0)print fp.readlines()fp.close()

>>> 

0

[‘aaaaa\n‘, ‘bbbbb\n‘, ‘ccccc‘]

19

[‘aaaaa\n‘, ‘bbbbb\n‘, ‘cccccddddd\n‘]

>>> 


本文出自 “今日的努力,明日的成功!” 部落格,請務必保留此出處http://zhzhgo.blog.51cto.com/10497096/1676562

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.