“行包含空字节"在 CSV 阅读器中 (Python) [英] "Line contains NULL byte" in CSV reader (Python)
问题描述
我正在尝试编写一个程序,该程序查看 .CSV 文件 (input.csv) 并仅重写以特定元素 (corrected.csv) 开头的行,如文本文件 (output.txt) 中所列).
I'm trying to write a program that looks at a .CSV file (input.csv) and rewrites only the rows that begin with a certain element (corrected.csv), as listed in a text file (output.txt).
这就是我的程序现在的样子:
This is what my program looks like right now:
import csv
lines = []
with open('output.txt','r') as f:
for line in f.readlines():
lines.append(line[:-1])
with open('corrected.csv','w') as correct:
writer = csv.writer(correct, dialect = 'excel')
with open('input.csv', 'r') as mycsv:
reader = csv.reader(mycsv)
for row in reader:
if row[0] not in lines:
writer.writerow(row)
不幸的是,我一直收到这个错误,我不知道它是怎么回事.
Unfortunately, I keep getting this error, and I have no clue what it's about.
Traceback (most recent call last):
File "C:Python32Sample ProgramcsvParser.py", line 12, in <module>
for row in reader:
_csv.Error: line contains NULL byte
感谢所有人这里 甚至让我走到这一步.
Credit to all the people here to even to get me to this point.
推荐答案
我已经用更简单的解决方案解决了类似的问题:
I've solved a similar problem with an easier solution:
import codecs
csvReader = csv.reader(codecs.open('file.csv', 'rU', 'utf-16'))
关键是使用 codecs 模块以 UTF-16 编码打开文件,还有更多的编码,请查看 文档.
The key was using the codecs module to open the file with the UTF-16 encoding, there are a lot more of encodings, check the documentation.
这篇关于“行包含空字节"在 CSV 阅读器中 (Python)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!