"_csv.Error: line contains NULL byte" in CSV reader from STDIN
Question: There are many StackOverflow questions about this error when reading from a
**_CSV_** file. My problem is occurring while reading from **_STDIN_**.

`[Most SO solutions talk about tweaking the open() command which works for
opening CSV files - not for reading them through STDIN]. My problem is with
reading through STDIN. So please don't mark this as a duplicate.`

My python code is:

    
    
    import sys , csv
    def main(argv): 
        reader = csv.reader(sys.stdin, delimiter=',')
        for line in reader:
            print line
    

and the returned error is:

    
    
    Traceback (most recent call last):
    File "mapper.py", line 19, in <module>
        main(sys.argv) 
    File "mapper.py", line 4, in main
        for line in reader:
    _csv.Error: line contains NULL byte
    

It would suffice me to simply ignore that line where the NULL byte occurs (if
that is possible) in the for loop.


Answer: i solved it by handling CSV exception

    
    
    import sys , csv    
    def main(argv): 
        reader      = csv.reader(sys.stdin, delimiter=',')
        lineCount   = 0
        errorCount  = 0
        while True:
            # keep iterating indefinitely until exception is raised for end of the reader (an iterator)
            try:
                lineCount += 1
                line = next(reader)
                print "%d - %s" % (lineCount , line)
            except csv.Error: 
                # this exception is raised when a malformed CSV is encountered... ignore it and continue
                errorCount += 1
                continue
            except StopIteration: 
                # this exception is raised when next() reaches the end of the iterator
                lineCount -= 1
                break
        print "total line: %d" % lineCount
        print "total error: %d" % errorCount
    

