2024-03-28 17:28:05 发布
网友
当涉及UTF-8/Unicode时,Python中的csv模块不能正常工作。在Python documentation和其他网页上,我发现了适用于特定情况的代码片段,但是您必须清楚地了解您正在处理的编码并使用适当的代码片段。
在Python2.6中,如何从.csv文件读取和写入字符串以及Unicode字符串?或者这是Python2.6没有简单解决方案的限制?
回答有点晚,但我使用unicodecsv非常成功。
在http://docs.python.org/library/csv.html#examples给出的关于如何读取Unicode的示例代码看起来已经过时,因为它不适用于Python 2.6和2.7。
下面是UnicodeDictReader,它可以与utf-8一起工作,也可以与其他编码一起工作,但我只在utf-8输入端测试过它。
UnicodeDictReader
简而言之,其思想是仅在csv行被csv.reader拆分为字段后解码Unicode。
csv.reader
class UnicodeCsvReader(object): def __init__(self, f, encoding="utf-8", **kwargs): self.csv_reader = csv.reader(f, **kwargs) self.encoding = encoding def __iter__(self): return self def next(self): # read and split the csv row into fields row = self.csv_reader.next() # now decode return [unicode(cell, self.encoding) for cell in row] @property def line_num(self): return self.csv_reader.line_num class UnicodeDictReader(csv.DictReader): def __init__(self, f, encoding="utf-8", fieldnames=None, **kwds): csv.DictReader.__init__(self, f, fieldnames=fieldnames, **kwds) self.reader = UnicodeCsvReader(f, encoding=encoding, **kwds)
用法(源文件编码为utf-8):
csv_lines = ( "абв,123", "где,456", ) for row in UnicodeCsvReader(csv_lines): for col in row: print(type(col), col)
输出:
$ python test.py <type 'unicode'> абв <type 'unicode'> 123 <type 'unicode'> где <type 'unicode'> 456
提供的模块here看起来是csv模块的一个很酷、简单的插件,它允许您使用utf-8csv。
import ucsv as csv with open('some.csv', 'rb') as f: reader = csv.reader(f) for row in reader: print row
回答有点晚,但我使用unicodecsv非常成功。
在http://docs.python.org/library/csv.html#examples给出的关于如何读取Unicode的示例代码看起来已经过时,因为它不适用于Python 2.6和2.7。
下面是
UnicodeDictReader
,它可以与utf-8一起工作,也可以与其他编码一起工作,但我只在utf-8输入端测试过它。简而言之,其思想是仅在csv行被
csv.reader
拆分为字段后解码Unicode。用法(源文件编码为utf-8):
输出:
提供的模块here看起来是csv模块的一个很酷、简单的插件,它允许您使用utf-8csv。
相关问题 更多 >
编程相关推荐