解决Python3读取csv文件中文报错问题
问题
今天在使用csv库的时候,出现报错,找到原因是csv文件含有中文,在读取中文的时候,格式出现问题。
test.py
import csv
with open ('test.csv','r') as file:
csv_file = csv.reader(file)
for row in csv_file:
print(row)
报错
Traceback (most recent call last):
File "test.py", line 5, in <module>
for row in csvFile:
File "/usr/lib/python3.5/csv.py", line 109, in __next__
self.fieldnames
File "/usr/lib/python3.5/csv.py", line 96, in fieldnames
self._fieldnames = next(self.reader)
File "/usr/lib/python3.5/codecs.py", line 321, in decode
(result, consumed) = self._buffer_decode(data, self.errors, final)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xb2 in position 27: invalid start byte
典型的编码解码出错,'utf-8’编码器出错,那显然就需要更换编码方式了。
方法一
更改编码格式为’gbk’
import csv
with open ('test.csv','r',encoding='gbk') as file:
csv_file = csv.reader(file)
for row in csv_file:
print(row)
方法二
将csv文件内容转移到新建的csv文件,亲测有效。