Python 3 - '_csv.Error: line contains NULL' error byte when reading csv file

有些话、适合烂在心里 提交于 2021-02-17 05:51:26

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!