Python3 读取utf8 档案

Phanix
·
·
IPFS
·

纪录一下,每次都忘记Orz

预设的话不是utf8 读档案,所以会喷类似这样的错误讯息

File “/usr/lib/python3.6/encodings/ascii.py”, line 26, in decode
return codecs.ascii_decode(input, self.errors)[0] UnicodeDecodeError: 'ascii' codec can't decode byte 0xe9 in position 29: ordinal not in range(128)

解法就是开启档案时加上encoding=”utf-8″

 with open(os.path.join("./", inputfile), "r", encoding="utf-8") as my_file:
    tree_text = my_file.read()

Original link: Phanix's Blog

CC BY-NC-ND 2.0 授权

喜欢我的作品吗?别忘了给予支持与赞赏,让我知道在创作的路上有你陪伴,一起延续这份热忱!