1. 程式人生 > >python 讀寫檔案函式open()用法

python 讀寫檔案函式open()用法

原文連結:http://www.jb51.net/article/58002.htm

1. open()語法

open(file[, mode[, buffering[, encoding[, errors[, newline[, closefd=True]]]]]])
open函式有很多的引數,常用的是file,mode和encoding
file檔案位置,需要加引號
mode檔案開啟模式,見下面3
buffering的可取值有0,1,>1三個,0代表buffer關閉(只適用於二進位制模式),1代表line buffer(只適用於文字模式),>1表示初始化的buffer大小;
encoding表示的是返回的資料採用何種編碼,一般採用utf8或者gbk;
errors

的取值一般有strict,ignore,當取strict的時候,字元編碼出現問題的時候,會報錯,當取ignore的時候,編碼出現問題,程式會忽略而過,繼續執行下面的程式。
newline可以取的值有None, \n, \r, ”, ‘\r\n',用於區分換行符,但是這個引數只對文字模式有效;
closefd的取值,是與傳入的檔案引數有關,預設情況下為True,傳入的file引數為檔案的檔名,取值為False的時候,file只能是檔案描述符,什麼是檔案描述符,就是一個非負整數,在Unix核心的系統中,開啟一個檔案,便會返回一個檔案描述符。

2. Python中file()與open()區別
兩者都能夠開啟檔案,對檔案進行操作,也具有相似的用法和引數,但是,這兩種檔案開啟方式有本質的區別,file為檔案類

,用file()來開啟檔案,相當於這是在構造檔案類,而用open()開啟檔案,是用python的內建函式來操作,建議使用open

3. 引數mode的基本取值

Character Meaning
‘r' open for reading (default)
‘w' open for writing, truncating the file first
‘a' open for writing, appending to the end of the file if it exists
‘b' binary mode
‘t' text mode (default)
‘+' open a disk file for updating (reading and writing)
‘U' universal newline mode (for backwards compatibility; should not be used in new code)

r、w、a為開啟檔案的基本模式,對應著只讀、只寫、追加模式;
b、t、+、U這四個字元,與以上的檔案開啟模式組合使用,二進位制模式,文字模式,讀寫模式、通用換行符,根據實際情況組合使用、

常見的mode取值組合

?
1 2 3 4 5 6 7 8 9 10 11 r或rt 預設模式,文字模式讀 rb   二進位制檔案 w或wt 文字模式寫,開啟前檔案儲存被清空 wb  二進位制寫,檔案儲存同樣被清空 a  追加模式,只能寫在檔案末尾 a+ 可讀寫模式,寫只能寫在檔案末尾 w+ 可讀寫,與a+的區別是要清空檔案內容 r+ 可讀寫,與a+的區別是可以寫到檔案任何位置

4. 測試
測試檔案test.txt,內容如下:

1 2 3 Hello,Python www.jb51.net This is a test file

用一小段程式碼來測試寫入檔案直觀的顯示它們的不同

test = [ "test1\n", "test2\n", "test3\n" ]
f = open("test.txt", "a+")
try:
 #f.seek(0)
 for l in test:
  f.write(l)
finally:
 f.close()

a+、w+和r+模式的區別(測試後還原test.txt)
a+模式

1 2 3 4 5 6 7 # cat test.txt Hello, Python www.jb51.net This is a test file test1 test2 test3

w+模式

1 2 3 4 # cat test.txt test1 test2 test3

r+模式
在寫入檔案前,我們在上面那段程式碼中加上一句f.seek(0),用來定位寫入檔案寫入位置(檔案開頭),直接覆蓋字元數(注意\n也是一個字元)

1 2 3 4 5 6 # cat test.txt test1 test2 test3 inuxeye.com This is a test file

注意:r+模式開啟檔案時,此檔案必須存在,否則就會報錯,‘r'模式也如此
其他測試

>>> f = open('test.txt')
>>> f.read() #讀取整個檔案,字串顯示
'Hello,Python\nwww.jb51.net\nThis is a test file\n'
>>> f.read() #指標在檔案末尾,不能再讀取內容
''
>>> f = open('test.txt')
>>> f.readline() #一次讀一行,指標在該行末尾
'Hello,Python\n'
>>> f.tell() #改行的字元長度
13
>>> f.readline()
'www.jb51.net\n'
>>> f.tell()
30
>>> f.readline()
'This is a test file\n'
>>> f.tell()
50
>>> f.readline()
''
>>> f.tell() #指標停在最後一行
50
>>> f = open('test.txt')
>>> f.readlines() #讀取整個檔案,以列表顯示
['Hello,Python\n', 'www.jb51.net\n', 'This is a test file\n']
>>> f.tell() #指標在最後一行
50
1 2 3 4 5 6 7 8 >>> f = open('test.txt','w') #覆蓋建立新檔案 >>> f.write('Hello,Python!') #如果寫入內容小於1024,會存在記憶體,否則需要重新整理 >>> f.flush() #寫入到硬碟 >>> f.close() #關閉檔案會自動重新整理 >>> f.write('Hello,Linuxeye') #關閉後,寫失敗,提示檔案已經關閉 Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: I/O operation on closed file