当前位置:   article > 正文

python写入csv编码报错_【笔记】Python读取各种编码的csv

import-export导入csv报错'utf-8' codec can't decode byte 0xb1 in position 4

Python csv库读取csv文件经常遇到莫名其妙的编码,报错信息如下:

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

于是造如下轮子,解析各种编码的csv文件,后续可持续追加各种编码。

如下:

def read_csv(filename):

encodings = ['gbk','utf-8','utf-8-sig','GB2312','gb18030',]

for e in encodings:

data = []

try:

with open(filename, encoding=e) as f:

reader = csv.reader(f)

header = next(reader)

# print(header)

for row in reader:

data.append(row)

print(filename,e)

return data

except:

print(filename,e)

print(filename,"==================")

return False

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/weixin_40725706/article/detail/175840
推荐阅读
相关标签
  

闽ICP备14008679号