Python 檔案讀取與寫入操作方法

來源:互聯網
上載者:User

F.read([size]) #size為讀取的長度,以byte為單位
F.readline([size])
#讀一行,如果定義了size,有可能返回的只是一行的一部分
F.readlines([size])
#把檔案每一行作為一個list的一個成員,並返回這個list。其實它的內部是通過迴圈調用readline()來實現的。如果提供size參數,size是表示讀取內容的總長,也就是說可能唯讀到檔案的一部分。
F.write(str)
#把str寫到檔案中,write()並不會在str後加上一個分行符號
F.writelines(seq)
#把seq的內容全部寫到檔案中。這個函數也只是忠實地寫入,不會在每行後面加上任何東西。
file的其他方法:


f=open('/tmp/workfile', 'w')
print f

讀檔案執行個體二

myfile = open('myfile', 'r')             # open for input

print myfile.readline()                        # read the line back

print myfile.readline()                        # empty string: end of file

myfile.close()

讀文字檔
input = open('data', 'r')
#第二個參數預設為r
input = open('data')
 
 

 

讀固定位元組
file_object = open('abinfile', 'rb')
try:
    while True:
         chunk = file_object.read(100)
        if not chunk:
            break
         do_something_with(chunk)
finally:
     file_object.close( )
 

 

讀每行
list_of_all_the_lines = file_object.readlines( )
如果檔案是文字檔,還可以直接遍曆檔案對象擷取每行:

for line in file_object:
     process line

 

向檔案中儲存內容

myfile = open('myfile', 'w')             # open for output (creates)

myfile.write('hello text filen')        # write a line of text

myfile.close()

其它

寫文字檔
output = open('data', 'w')
寫二進位檔案
output = open('data', 'wb')
 

追加寫檔案

output = open('data', 'w+')
 

 

寫資料
file_object = open('thefile.txt', 'w')
file_object.write(all_the_text)
file_object.close( )
 


寫入多行
file_object.writelines(list_of_text_strings)


F.close()
#關閉檔案。python會在一個檔案不用後自動關閉檔案,不過這一功能沒有保證,最好還是養成自己關閉的習慣。如果一個檔案在關閉後還對其進行操作會產生ValueError
F.flush()
#把緩衝區的內容寫入硬碟
F.fileno()
#返回一個長整型的”檔案標籤“
F.isatty()
#檔案是否是一個終端裝置檔案(unix系統中的)
F.tell()
#返迴文件操作標記的當前位置,以檔案的開頭為原點
F.next()
#返回下一行,並將檔案操作標記位移到下一行。把一個file用於for ... in file這樣的語句時,就是調用next()函數來實現遍曆的。
F.seek(offset[,whence])
#將檔案打操作標記移到offset的位置。這個offset一般是相對於檔案的開頭來計算的,一般為正數。但如果提供了whence參數就不一定了,whence可以為0表示從頭開始計算,1表示以當前位置為原點計算。2表示以檔案末尾為原點進行計算。需要注意,如果檔案以a或a+的模式開啟,每次進行寫操作時,檔案操作標記會自動返回到檔案末尾。
F.truncate([size])

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.