下面我有一个字符串,表示从csv文件中提取的单行。每列用逗号分隔,值包含在“”中。解析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"
以上数据都是一个需要拆分成列的大字符串,因此我可以获取值。我不是在问如何加载csv文件。已经找到了那个部分。
答案 0 :(得分:16)
Python有一个模块:
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))