问题

学习 python IO 文件读写时,使用以下方式打开 txt 文本文件(文件本身编码格式 utf-8)。文件内容为英文时,正常获取到,内容为中文时就会报错:UnicodeDecodeError: 'gbk' codec can't decode byte 0xa1 in position 4: illegal multibyte sequence。代码如下:

with open('d:/files/test.txt', 'r') as f:
    print(f.read())

其中, withtry...finally 的简写形式。

解决

使用二进制方式打开文件

with open('d:/files/test.txt', 'rb') as f:
    print(f.read())

明确文件编码方式为 utf-8

with open('d:/files/test.txt', 'r', encoding='utf-8') as f:
    print(f.read())

其中的 encoding 值,大小写和短杠都可以忽略。

两种形式不能混用,否则回报 ValueError 错误:ValueError: binary mode doesn't take an encoding argument

文章目录