Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
630 views
in Technique[技术] by (71.8m points)

parse comma separated csv file with quotes in python

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...