文件 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")