Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I am trying to import a .csv file, clean the contents, and make sure all the errors are eliminated.

  • IO error
  • file format error
  • data error

I am using the snippet below. Could someone help me clean it and make it more pythonic?

    fl = request.FILES['csv']
    return HttpResponse("Some IO Error")
    reader = csv.reader(fl)
    return HttpResponse("File Not Supported") # this makes sure the heading is 
cleaned_csv_content = list()
for row in reader:
    err = 0
    fname, lname, e_mail  = row
        err = 1
    if not err:
        cleaned_csv_content.append(fname, lname, e_mail)
share|improve this question

Firstly, you should raise not return your errors.

Secondly, try: with a bare except: is bad practice (e.g.; what do you expect could go wrong with each step? Test for specific errors and deal with them appropriately. It is this which has hidden the NameError I mention at the end.

Thirdly, your use of the flag err seems a bit odd; much more Pythonic to use an actual boolean err = False or, better, else::

    validate_email(e_mail) # see comment below
except: # but only the errors you expect - see above 
    cleaned_csv_content.append((fname, lname, e_mail)) # note additional parentheses

or, even better, refactor validate_email to return True for a valid email and False otherwise, rather than raising errors:

if validate_email(e_mail):
    cleaned_csv_content.append((fname, lname, e_mail))

Finally, note that "email" != "e_mail".

share|improve this answer
how about the for loops, can that be made more idiomatic? – Ram Kumar Dec 13 '13 at 10:36
No; for row in reader: is fine and the tuple unpacking of each row is very Pythonic – jonrsharpe Dec 13 '13 at 10:38
I am getting this error - Error: 'line contains NULL byte' for row in reader Any corrections? – Ram Kumar Dec 13 '13 at 10:43
Not to the code, as such; you will need to look at your input data and what is ending up in reader, or use another try and handle that specific error appropriately (e.g. pass on that line). – jonrsharpe Dec 13 '13 at 10:51
thanks done, another doubt. I am getting output of - for row in readline: print row as follows ['First Name\tLast Name\tEmail Address'] ['ASdf \tasdf\tasdf@asdf.asdf'] The delimiter here is \t, any idea how to fix it? – Ram Kumar Dec 13 '13 at 11:29

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.