1

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

2
  • Can you post your CSV? Commented Apr 12, 2018 at 10:36
  • I added a link to the relevant section Commented Apr 12, 2018 at 10:54

2 Answers 2

4

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 
Sign up to request clarification or add additional context in comments.

2 Comments

Working great! It's a little bit slower now but it's done the trick Thanks very much!
this has worked for me too.Thanks and yes looks bit slow. but fine.
0

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 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.