檔案 IO

以非二進位制模式開啟的檔案(例如'r''w')處理字串。deafult 編碼是'utf8'

open(fn, mode='r')                    # opens file for reading in utf8
open(fn, mode='r', encoding='utf16')  # opens file for reading utf16

# ERROR: cannot write bytes when a string is expected:
open("foo.txt", "w").write(b"foo")

以二進位制模式開啟的檔案(例如'rb''wb')處理位元組。由於沒有編碼,因此無法指定編碼引數。

open(fn, mode='wb')  # open file for writing bytes

# ERROR: cannot write string when bytes is expected:
open(fn, mode='wb').write("hi")