讀文件:
f = open('/Users/michael/test.txt', 'r') #一次讀取文件的全部內容 f.read() #文件使用完畢后必須關閉,因為文件對象會占用操作系統的資源,並且操作系統同一時間能打開的文件數量也是有限的 close() #考慮異常,無論是否出錯都能正確地關閉文件 try: f = open('/path/to/file', 'r') print(f.read()) finally: if f: f.close() #等價於 with語句來自動幫我們調用close()方法 with open('/path/to/file', 'r') as f: print(f.read()) #二進制文件 f = open('/Users/michael/test.jpg', 'rb') #字符編碼 #要讀取非UTF-8編碼的文本文件,需要給open()函數傳入encoding參數,例如,讀取GBK編碼的文件: f = open('/Users/michael/gbk.txt', 'r', encoding='gbk') #遇到有些編碼不規范的文件,你可能會遇到UnicodeDecodeError,直接忽略 f = open('/Users/michael/gbk.txt', 'r', encoding='gbk', errors='ignore'
寫文件:
#傳入標識符'w'或者'wb'表示寫文本文件或寫二進制文件 f = open('/Users/michael/test.txt', 'w') f.write('Hello, world!') f.close() #要寫入特定編碼的文本文件,請給open()函數傳入encoding參數 with open('/Users/michael/test.txt', 'w') as f: f.write('Hello, world!')
最好使用with
語句
StringIO和BytesIO是在內存中操作str和bytes的方法,使得和讀寫文件具有一致的接口
StringIO和BytesIO
str的讀取:
#寫入字符串 from io import StringIO f = StringIO() f.write(''Hello!\nHi!\nGoodbye!'') #getvalue()方法用於獲得寫入后的str print(f.getvalue()) #或者行讀 while True: s = f.readline() if s == '': break print(s.strip()) #結果 Hello! Hi! Goodbye!
二進制的讀取:
from io import BytesIO #寫 f = BytesIO() #經過UTF-8編碼的bytes f.write('中文'.encode('utf-8')) print(f.getvalue()) #結果 b'\xe4\xb8\xad\xe6\x96\x87 #讀 f = BytesIO(b'\xe4\xb8\xad\xe6\x96\x87') f.read() #結果 b'\xe4\xb8\xad\xe6\x96\x87'