CSV模块
有如下文本
Symbol,Price,Date,Time,Change,Volume "AA",39.48,"6/11/2007","9:36am",-0.18,181800 "AIG",71.38,"6/11/2007","9:36am",-0.15,195500 "AXP",62.58,"6/11/2007","9:36am",-0.46,935000 "BA",98.31,"6/11/2007","9:36am",+0.12,104800 "C",53.08,"6/11/2007","9:36am",-0.25,360900 "CAT",78.29,"6/11/2007","9:36am",-0.23,225400
使用字符串下标取某一列
import csv from collections import namedtuple with open('l.csv','r') as f: fcsv = csv.reader(f,delimiter=',') header = next(f) Row = namedtuple('Row', header) for i in fcsv: row = Row(*i)
row.Date 输出: 6/11/2007 6/11/2007 6/11/2007 6/11/2007 6/11/2007 6/11/2007 row 输出: Row(Symbol='AA', Price='39.48', Date='6/11/2007', Time='9:36am', Change='-0.18', Volume='181800') Row(Symbol='AIG', Price='71.38', Date='6/11/2007', Time='9:36am', Change='-0.15', Volume='195500') Row(Symbol='AXP', Price='62.58', Date='6/11/2007', Time='9:36am', Change='-0.46', Volume='935000') Row(Symbol='BA', Price='98.31', Date='6/11/2007', Time='9:36am', Change='+0.12', Volume='104800') Row(Symbol='C', Price='53.08', Date='6/11/2007', Time='9:36am', Change='-0.25', Volume='360900') Row(Symbol='CAT', Price='78.29', Date='6/11/2007', Time='9:36am', Change='-0.23', Volume='225400')
使用字典取某一列
import csv with open('l.csv','r') as f: fcsv = csv.DictReader(f) for i in fcsv: print i['Symbol'] 输出: {'Symbol': 'AA', 'Volume': '181800', 'Time': '9:36am', 'Date': '6/11/2007', 'Price': '39.48', 'Change': '-0.18'} {'Symbol': 'AIG', 'Volume': '195500', 'Time': '9:36am', 'Date': '6/11/2007', 'Price': '71.38', 'Change': '-0.15'} {'Symbol': 'AXP', 'Volume': '935000', 'Time': '9:36am', 'Date': '6/11/2007', 'Price': '62.58', 'Change': '-0.46'} {'Symbol': 'BA', 'Volume': '104800', 'Time': '9:36am', 'Date': '6/11/2007', 'Price': '98.31', 'Change': '+0.12'} {'Symbol': 'C', 'Volume': '360900', 'Time': '9:36am', 'Date': '6/11/2007', 'Price': '53.08', 'Change': '-0.25'} {'Symbol': 'CAT', 'Volume': '225400', 'Time': '9:36am', 'Date': '6/11/2007', 'Price': '78.29', 'Change': '-0.23'}
写CSV文件
import csv headers = ['aa','bb','cc','dd'] rows = [{'aa':'111','bb':'222','cc':'333','dd':'444'}, {'aa':'1111','bb':'2222','cc':'3333','dd':'4444'} ] with open('tt.csv','w') as f: f_csv = csv.DictWriter(f, headers) f_csv.writeheader() f_csv.writerows(rows) cat tt.csv aa,bb,cc,dd 111,222,333,444 1111,2222,3333,4444