csv read _csv.Error: line contains NULL byte

Tim Golden mail at timgolden.me.uk
Fri Mar 21 10:59:01 EDT 2014


On 21/03/2014 14:46, chip9munk at gmail.com wrote:
> I am sorry I do not understand how to get to each row in this way.
> 
> Please could you explain also this:
> If I define this function, 
> how do I change my for loop to get each row?

Does this help?

<code>
#!python3
import csv

def unfussy_reader(csv_reader):
    while True:
        try:
            yield next(csv_reader)
        except csv.Error:
            # log the problem or whatever
            print("Problem with some row")
            continue

if __name__ == '__main__':
    #
    # Generate malformed csv file for
    # demonstration purposes
    #
    with open("temp.csv", "w") as fout:
        fout.write("abc,def\nghi\x00,klm\n123,456")

    #
    # Open the malformed file for reading, fire up a
    # conventional CSV reader over it, wrap that reader
    # in our "unfussy" generator and enumerate over that
    # generator.
    #
    with open("temp.csv") as fin:
        reader = unfussy_reader(csv.reader(fin))
        for n, row in enumerate(reader):
            print(n, "=>", row)


</code>


TJG



More information about the Python-list mailing list