更新:尽管我原先回答中的代码是可行的,但我现在已经发布了一个小包
https://pypi.python.org/pypi/csv342,该包为Python 2提供了类似于Python 3的接口。因此,无论您使用的是哪个Python版本,都可以简单地执行以下操作。
import csv342 as csv
import io
with io.open('some.csv', 'r', encoding='utf-8', newline='') as csv_file:
for row in csv.reader(csv_file, delimiter='|'):
print(row)
以下是一个即使在Python 2中也将文本解码为Unicode字符串并因此与UTF-8以外的编码一起使用的解决方案。
下面的代码定义了一个名为
csv_rows()
的函数,该函数将文件内容作为列表序列返回。例如用法:
for row in csv_rows('some.csv', encoding='iso-8859-15', delimiter='|'):
print(row)
以下是`csv_rows()`的两个变体:一个适用于Python 3+,另一个适用于Python 2.6+。在运行时它会自动选择正确的变体。`UTF8Recoder`和`UnicodeReader`是
Python 2.7库文档中的示例的逐字拷贝。
import csv
import io
import sys
if sys.version_info[0] >= 3:
def csv_rows(csv_path, encoding, **keywords):
with io.open(csv_path, 'r', newline='', encoding=encoding) as csv_file:
for row in csv.reader(csv_file, **keywords):
yield row
else:
import codecs
class UTF8Recoder:
"""
Iterator that reads an encoded stream and reencodes the input to UTF-8
"""
def __init__(self, f, encoding):
self.reader = codecs.getreader(encoding)(f)
def __iter__(self):
return self
def next(self):
return self.reader.next().encode("utf-8")
class UnicodeReader:
"""
A CSV reader which will iterate over lines in the CSV file "f",
which is encoded in the given encoding.
"""
def __init__(self, f, dialect=csv.excel, encoding="utf-8", **kwds):
f = UTF8Recoder(f, encoding)
self.reader = csv.reader(f, dialect=dialect, **kwds)
def next(self):
row = self.reader.next()
return [unicode(s, "utf-8") for s in row]
def __iter__(self):
return self
def csv_rows(csv_path, encoding, **kwds):
with io.open(csv_path, 'rb') as csv_file:
for row in UnicodeReader(csv_file, encoding=encoding, **kwds):
yield row
sys.version
并在你的代码周围包装一个if - else
语句。 - Tim Pietzcker