Python 读取文件报错:UnicodeEncodeError: 'latin-1' codec can't encode character

# UnicodeEncodeError: 'latin-1' codec can't encode character

例如:

file = open("xxx.txt","r",encoding="utf-8")

for line in file:
    print(line)

UnicodeEncodeError: 'latin-1' codec can't encode character

修改方式:

file = open("xxx.txt","r",encoding="utf-8")

for line in file:
    line=line.encode("utf-8").decode("latin1")
    print(line)

另外,可能是因为python默认编码是  latin1

可以更改环境变量:

export PYTHONIOENCODING=utf-8

你可能感兴趣的:(python,python常见错误)