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取值組合
r或rt 預設模式,文字模式讀rb 二進位檔案 w或wt 文字模式寫,開啟前檔案儲存體被清空wb 二進位寫,檔案儲存體同樣被清空 a 追加模式,只能寫在檔案末尾a+ 可讀寫入模式,寫只能寫在檔案末尾 w+ 可讀寫,與a+的區別是要清空檔案內容r+ 可讀寫,與a+的區別是可以寫到檔案任何位置
4. 測試
測試檔案test.txt,內容如下:
Hello,Pythonwww.jb51.netThis 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+模式
# cat test.txtHello, Pythonwww.jb51.netThis is a test filetest1test2test3
w+模式
# cat test.txttest1test2test3
r+模式
在寫入檔案前,我們在上面那段代碼中加上一句f.seek(0),用來定位寫入檔案寫入位置(檔案開頭),直接覆蓋字元數(注意\n也是一個字元)
# cat test.txttest1test2test3inuxeye.comThis 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
>>> f = open('test.txt','w') #覆蓋建立新檔案>>> f.write('Hello,Python!') #如果寫入內容小於1024,會存在記憶體,否則需要重新整理>>> f.flush() #寫入到硬碟>>> f.close() #關閉檔案會自動重新整理>>> f.write('Hello,Linuxeye') #關閉後,寫失敗,提示檔案已經關閉Traceback (most recent call last): File "", line 1, in ValueError: I/O operation on closed file