问题
I'm trying to read a csv file that contains NUL with csv reader I search a lot for a way to read the file without an error and couldn't find one.
Edit: Adding the relevant section of the file: https://drive.google.com/open?id=1rtF3ck6QymtH4_n4iUjavPnxZiryq_Q4
My code:
with codecs.open(log_path, 'r') as csv_file:
log_reader = csv.DictReader(csv_file)
for line in log_reader:
if line['Addition Information'] == str
# do something
Will appreciate any help Thanks, Avishay
回答1:
csv.reader() (and therefore also csv.DictReader()) simply can't deal with files containing null bytes.
A possible solution would be to replace null bytes when reading the input file, e.g. by using a generator expression, since reader()
takes any object supporting the iterator protocol as argument:
with codecs.open(log_path, 'r') as csv_file:
log_reader = csv.DictReader((l.replace('\0', '') for l in csv_file))
for line in log_reader:
if line['Addition Information'] == str
# do something
回答2:
Try to modify your code like this:
with codecs.open(log_path, 'r', encoding='utf-8', errors='backslashreplace') as csv_file:
log_reader = csv.DictReader(csv_file)
for line in log_reader:
if line['Addition Information'] == str
# do something
来源:https://stackoverflow.com/questions/49794302/python-3-csv-error-line-contains-null-error-byte-when-reading-csv-file