2

I'm trying to catch a Null Byte Exception in the last line of a CSV file:

def Catch(csv_filename):
    with open(csv_filename,'r+') as File:
        File_reader = csv.reader(File,delimiter="\t",dialect='excel-tab')
        a = []
        for row in File_reader:
            try:
                a.append(row)
            except csv.Error:
                return "Error"

Catch("/../DataLogger.csv")

but an _csv.Error is raised:

Traceback (most recent call last):
File "/../test.py", line 21, in <module>
Catch("/../DataLogger.csv")
File "/../test.py", line 13, in Catch
for row in File_reader:
    _csv.Error: line contains NULL byte

I don't get why the exception is not catched with the function. I'm using python 3.4

2 Answers 2

2

that's because the exception occurs as soon as your code reaches the for statement.

No exception can happen in the a.append line, the csv module does its job in the iteration of the for loop.

Once you know that, the fix is trivial:

try:
   for row in File_reader:
       a.append(row)
except csv.Error:
    return "Error"

note that one could be tempted to use direct conversion to list: a = list(File_reader) but since the exception would take place in the list conversion, a wouldn't be filled, which would be a nuisance if the start of the file contains useful data you want to read (but since you're returning an error string, it doesn't seem to matter here)

Sign up to request clarification or add additional context in comments.

1 Comment

I found that _csv.Error is raised even before iterating the content of csv.reader. For example: reader = csv.reader(csvfile, delimiter=options.get('csv_separator', ',')) raises if csvfile contains null byte.
1
def Catch(csv_filename):
    with open(csv_filename,'r+') as File:
        try:
            File_reader = csv.reader(File,delimiter="\t",dialect='excel-tab')
            a = []
            for row in File_reader:
                a.append(row)
        except csv.Error
            return "Error"

Catch("/../DataLogger.csv")

The whole parsing has to be inside Try/catch, instead of only a.append.

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.