【发布时间】:2017-12-23 00:10:03
【问题描述】:
我已经阅读了所有与 unicode 阅读相关的主题,但我似乎无法让它发挥作用。
我正在尝试读取一个恰好有 utf-8 BOM 签名并且也是 utf-8 的 csv。
所以,打开文件后,使用 unicodecsv 库读取它,我尝试了不同的方法。
def _extract_gz(self): # fd
logging.info("Gz detected")
self.fp = gzip.open(self.path)
return unicodecsv.reader(self.path.read().decode('utf-8-sig').splitlines(), encoding='utf-8')
在第 226 行仍然失败。UnicodeEncodeError: 'ascii' codec can't encode character u'\xf1' in position 226: ordinal not in range(128)
也尝试过这种方法,但也失败了。
def _extract_gz(self): # fd
logging.info("Gz detected")
self.fp = gzip.open(self.path)
self.f = self.unicode_csv_reader()
return self.f
def unicode_csv_reader(self):
csv_reader = csv.reader(self.fp.read().decode('utf-8-sig').splitlines())
for row in csv_reader:
yield [cell.encode('utf-8', 'replace') for cell in row]
我做错了什么?
谢谢大家。
版本是Python 2.7.12
【问题讨论】:
-
我知道 unicodecsv 必须是 bytearray。我也尝试过这种方法:
codedef _extract_gz(self): # fd logging.info("Gz detected") self.fp = gzip.open(self.path) self.f = unicodecsv.reader(bytearray(self. fp.read()) return self.f 似乎所有的格式都正确但是,一旦我执行 f.next() 读取标题,就会出现这个错误。TypeError: expected string or Unicode object, int found即使打印 type(f) 返回 unicodecsv.py2.UnicodeReader -
如果您使用 CSV 并且遇到 UTF 问题,最好放置 python-2 或 python-3 标签,因为我记得不同(和棘手)的行为差异。
-
感谢@MariusSiuram 的回复,您指的是哪些标签?
-
我指的是您问题中的 StackOverflow 标签。此外,您可以编辑(可以吗?)以指定您的确切 python 版本。
-
已更新。谢谢!
标签: python python-2.7 csv unicode gzip