UnicodeDecodeError: 'utf-8' codec can't decode byte 0xb1 in position 0: invalid start byte问题的解决方案

近期使用python处理数据,使用python3打开一个txt文件

file1 = open("wenjianming.txt",'r')
data = file1.readlines()
i = ""
for i in data:
    print(i)

报错如下:

UnicodeDecodeError: 'utf-8' codec can't decode byte 0xb1 in position 0: invalid start byte

是编码的问题,所以将编码改成gbk试了一下

file1 = open("31省市居民家庭消费水平-city.txt",'r','gbk')

报错如下:

TypeError: an integer is required (got type str)

又继续百度,查了一下open函数:

open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)

也就是说在encoding参数前面还得有个buffering,参数值要是个整数,所以改成以下形式:

file1 = open("31省市居民家庭消费水平-city.txt",'r',1,'gbk')
data = file1.readlines()
i = ""
for i in data:
    print(i)

就能够正常输出汉字了

你可能感兴趣的:(python,问题解决)