欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Python读取中文文件报错UnicodeDecodeError: 'gbk' codec can't decode byte 0xaf in position 64

程序员文章站 2022-05-28 12:58:40
...

python读取包含中文的文件报错:UnicodeDecodeError: ‘gbk’ codec can’t decode byte 0xaf in position 64: illegal multibyte sequence

解决方法:打开文件时添加 encoding=’utf-8’ 进行编码即可
原程序:

with open('test.txt','r') as file:
    file=file.readlines()
    print(file)
    for i in file:
        print(i)
        break

修改后:

with open('test.txt','r',encoding='utf-8') as file:
    file=file.readlines()
    print(file)
    for i in file:
        print(i)
        break