【发布时间】:2016-02-14 03:21:36
【问题描述】:
我有以下代码读取 csv 文件(一些包含非 UTF8 字符)。它在 Python 2.7.x 中运行良好:
encodings = {'ukprocessed.csv': 'utf8',
'usprocessed.csv': 'utf8',
'uyprocessed.csv': 'latin1',
'arprocessed.csv': 'latin1'}
with codecs.open(filepath, 'r') as csvfile:
reader = csv.reader(csvfile)
for row in reader:
row = [x.decode(encodings[filename]).encode('utf8') for x in row]
但是,在 Python 3.4.x 中,测试失败并出现各种错误:
- AttributeError: 'str' 对象没有属性 'decode'
- UnicodeDecodeError:“ascii”编解码器无法解码位置 1078 中的字节 0xf1:序数不在范围内 (128) 等等……
我尝试在打开的文件中指定 'encoding=',使用 'rb' 和其他一些东西作为字节打开,但我找不到适用于 Python 2 和 3 的解决方案。
有人对我如何解决这个问题有任何想法吗?
谢谢
【问题讨论】:
标签: python python-2.7 csv python-3.x unicode