我正在尝试为 babel 编写自定义提取方法,以从 csv 文件的特定列中提取字符串。我遵循了文档 here .
这是我的提取方法代码:
def extract_csv(fileobj, keywords, comment_tags, options):
import csv
reader = csv.DictReader(fileobj, delimiter=',')
for row in reader:
if row and row['caption'] != '':
yield (reader.line_num, '', row['caption'], '')
当我尝试运行提取时出现此错误:
File "/Users/tiagosilva/repos/naltio/csv_extractor.py", line 18, in extract_csv for row in reader: File "/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/csv.py", line 111, in next self.fieldnames File "/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/csv.py", line 98, in fieldnames self._fieldnames = next(self.reader) _csv.Error: iterator should return strings, not bytes (did you open the file in text mode?)
传递给函数的 fileobj 似乎是以二进制模式打开的。
如何实现?我可以想到 2 种可能的解决方案,但我不知道如何对它们进行编码:
1) 有没有办法将它与 DictReader 一起使用?
2) 有没有办法通知 babel 以文本模式打开文件?
我对其他未列出的解决方案持开放态度。
最佳答案
我真的找到了一种方法!
这是解决方案 1,一种处理二进制文件的方法。解决方案是在二进制文件周围包装一个 TextIOWrapper 并将其解码并将其传递给 DictReader。
import csv
import io
with io.TextIOWrapper(fileobj, encoding='utf-8') as text_file:
reader = csv.DictReader(text_file, delimiter=',')
for row in reader:
if row and 'caption' in row.keys():
yield (reader.line_num, '', row['caption'], '')
关于python - 如何将 python csv.DictReader 与二进制文件一起使用? (对于一个babel自定义提取方法),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51152023/