IO編程-----讀寫文件
阿新 • • 發佈:2017-12-12
文件 tom lines 返回 編碼 python open for 產生 操作系統
讀寫文件是最常見的IO操作。Python內置了讀寫文件的函數,用法和C是兼容的。
讀寫文件前,我們先必須了解一下,在磁盤上讀寫文件的功能都是由操作系統提供的,現代操作系統不允許普通的程序直接操作磁盤,所以,讀寫文件就是請求操作系統打開一個文件對象(通常稱為文件描述符),然後,通過操作系統提供的接口從這個文件對象中讀取數據(讀文件),或者把數據寫入這個文件對象(寫文件)。
open
(file, mode=‘r‘, buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)
mode是一個可選字符串,用於指定打開文件的模式。 它默認‘r‘
打開文本模式下的閱讀方式。其他常見的值是‘w‘
寫(截斷文件,如果它已經存在),‘x‘
獨占創建和‘a‘
附加(在一些 Unix系統上,這意味著所有的寫入追加到文件的末尾,無論當前的尋找位置)。在文本模式下,如果 編碼未指定使用的編碼是與平臺相關的: locale.getpreferredencoding(False)
被稱為獲取當前的本地編碼。(用於讀取和寫入原始字節使用二進制模式,並保留 編碼未指定。)可用的模式是:
Character | Meaning |
---|---|
‘r‘ |
open for reading (default) 打開文件閱讀 |
‘w‘ |
open for writing, truncating the file first 打開並寫入文件 |
‘x‘ |
open for exclusive creation, failing if the file already exists 創建文件,如果 |
‘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 newlines mode (deprecated) |
#讀取文件 f=open(‘/home/wangxy/PycharmProjects/hello.txt‘, ‘r‘) #open(文件路徑,r表示讀) print(f.read())#成功open後,讀取內容 f.close() #文件使用完畢必須關閉,因為文件對象會占用系統資源 #由於文件讀寫時都有可能產生IOError,一旦出錯,後面的f.close()就不會調用。所以,為了保證無論是否出錯都能正確地關閉文件,我們可以使用with語句 #with語句會自動調用close with open(‘/home/wangxy/PycharmProjects/hello.txt‘, ‘r‘) as f: print(f.read()) with open(‘/home/wangxy/文檔/test.py‘,‘r‘) as f: #調用read()會一次性讀取文件的全部內容,如果文件有10G,內存就爆了,所以,要保險起見,可以反復調用read(size)方法,每次最多讀取size個字節的內容。 #print(f.read(512)) #是否可讀 print(‘readable is: %s‘%f.readable()) #readline(x) 讀一行,x表示讀幾個字節的內容 print(f.readline()) print(f.readline()) #readlines() 一次性讀取所有內容並按行返回list print(f.readlines()) #讀取二進制文件,比如圖片視頻,需要標識符為rb with open(‘/home/wangxy/圖片/1.png‘,‘rb‘) as f: print(f.read()) #遇到有些編碼不規範的文件,你可能會遇到UnicodeDecodeError,因為在文本文件中可能夾雜了一些非法編碼的字符。遇到這種情況,open()函數還接收一個errors參數,表示如果遇到編碼錯誤後如何處理。最簡單的方式是直接忽略: with open(‘/home/wangxy/文檔/Command方法分析.py‘,‘r‘,encoding=‘gbk‘,errors=‘ignore‘) as f: print(f.read()) #練習:請將本地一個文本文件讀為一個str並打印出來: fpath=r‘/home/wangxy/文檔/test.py‘ with open(fpath,‘r‘) as f: print(f.read())
#寫入文件 with open(‘/home/wangxy/PycharmProjects/hello.txt‘,‘a‘) as f: f.write(‘This is write line2!\n‘) #創建文件 with open(‘/home/wangxy/PycharmProjects/testwangxy.txt‘,‘x‘) as f: f.write(‘test create a file!‘)
IO編程-----讀寫文件