檔案 IO

file 不再是 3.x 中的內建名稱(open 仍然有效)。

檔案 I / O 的內部細節已經移動到標準庫 io 模組,這也是 StringIO 的新家:

import io
assert io.open is open # the builtin is an alias
buffer = io.StringIO()
buffer.write('hello, ') # returns number of characters written
buffer.write('world!\n')
buffer.getvalue() # 'hello, world!\n'

檔案模式(文字與二進位制)現在確定通過讀取檔案(以及寫入所需的型別)生成的資料型別:

with open('data.txt') as f:
    first_line = next(f)
    assert type(first_line) is str
with open('data.bin', 'rb') as f:
    first_kb = f.read(1024)
    assert type(first_kb) is bytes

文字檔案的編碼預設為 locale.getpreferredencoding(False) 返回的任何內容。要明確指定編碼,請使用 encoding 關鍵字引數:

with open('old_japanese_poetry.txt', 'shift_jis') as text:
    haiku = text.read()