9

Below i have a string which represents a single row pulled from a csv file. Each column is separated by a comma and the value is wrapped in "". What is the simplest way to parse out the value from each column in python?

"Mr","Bob","","Boberton","","President","","","","Blah, Inc. of Iowa","blah blah blah","","Grand Island","Hall County","NE","68801","7228","United States","308-111-1111","","","P.O. BOX 1111","","Grand Island","Hall County","NE","11111","1111","United States","","40.00000","-98.0000","Gasoline service stations","11111","1010101010","","","false","SINGLE_LOCATION","","","","","","","","","No","No","No","Owns","No","No","","","55.125905","","0.052369","","100","","100","0","","","1971","Low Risk","Convenience Stores & Truck Stops","1111111","1111111","111111","1111111"

The above data is all one big string that needs to be split into columns so i can get the values. I'm not asking how to load a csv file. Already got that part figured out.

2
  • 9
    Use csv. Indeed, before using csv try searching Stack Overflow for similar questions on parsing CSV since all those questions have code examples already written. Commented Jul 5, 2011 at 17:49
  • 2
    docs.python.org/library/csv.html Commented Jul 5, 2011 at 17:52

1 Answer 1

16

Python has a module for that:

http://docs.python.org/library/csv.html

import csv, sys
filename = 'some.csv'
with open(filename, 'rb') as f:
    reader = csv.reader(f)
    try:
        for row in reader:
            print row
    except csv.Error, e:
        sys.exit('file %s, line %d: %s' % (filename, reader.line_num, e))
Sign up to request clarification or add additional context in comments.

6 Comments

This helps, but how do I get a value from a specific column?
@Sam: Each row is a list with one entry per column.
@Sam: alternatively, the csv module has a DictReader class which will read the data into a Dict
I am parsing the csv file using app engine's blob_reader. Each row is a string, so basically I'm wondering what regex I should use to get the values.
Never mind. I was able to load what app engine gave me with the csv module.
|

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.