Python — CSV Reader. Basic / Bare Minimum Usage

This is a quick post about the standard library ‘csv’ in python. Absolute bare minimum usage to parse some CSV.

I’ve been using this or my own version of csv to process email lists, inventory histories, etc. Any time a spreadsheet is used, you can easily save it as a csv and load it up in python.

I do a lot of number crunching / processing that’s just too complicated to do easily in a spreadsheet, but data often comes in spreadsheets.

Example of usage in the python shell:

import csv
f = open('path/to/my/file', 'r') # open the file
reader = csv.reader(f)
reader.next() # prints the next ROW, as a list.
for row in reader:
         name = row[0]
         email = row[1]
         if email_validation(email): 
               #  do some logic to check against an ignore list, or what have you.
               save_email_or_smth(email, name)
f.close() # close the file.

3 Comments

  1. boorhin says:

    You don’t need to open the file with csv reader.

    Boorhin

    1. boorhin says:

      I was a bit straight but I meant you can write:
      reader = csv.reader(open(‘path/to/my/file’, ‘rU’), delimiter=’\t’, quoting=csv.QUOTE_NONE

      For a tab separated file

      So you don’t have to load the file in memory as a whole.

      1. Yuji says:

        Hey boorhin – in that case, is the file automatically closed?

Leave a Comment