CSV数据的读取十分地简单
分为两部分
读
读取csv文件可以使用csv模块下的reader(f)以及DictReader(f)
mport csv with open("text.csv","r") as f: f = csv.reader(f) for row in f: print(row)
结果表示为
['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']
而使用DictReader()来读取文件方便的一点在于可以使用索引的方式获取信息
import csv with open("text.csv","r") as f: f = csv.DictReader(f) for row in f: print(row["Symbol"],row["Price"],row["Date"],row["Time"],row["Change"])
其结果边表示为
AA 39.48 6/11/2007 9:36am -0.18 AIG 71.38 6/11/2007 9:36am -0.15 AXP 62.58 6/11/2007 9:36am -0.46 BA 98.31 6/11/2007 9:36am +0.12 C 53.08 6/11/2007 9:36am -0.25 CAT 78.29 6/11/2007 9:36am -0.23
区别:看个人喜好,喜欢哪种用哪种,但是以后应该会接触到根据不同的应用场景选择读取方式的场景。
写
写csv文件的时候需要注意一点
首先要写入csv文件的头部信息
随后再写入尾部信息
分为两种情况
一
headers = ['Symbol','Price','Date','Time','Change','Volume'] rows = [('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), ] with open('stocks.csv','w') as f: f_csv = csv.writer(f) f_csv.writerow(headers) f_csv.writerows(rows)
二
当row中时字典时,就可以选择使用DictWriter写入数据
headers = ['Symbol', 'Price', 'Date', 'Time', 'Change', 'Volume'] rows = [{'Symbol':'AA', 'Price':39.48, 'Date':'6/11/2007', 'Time':'9:36am', 'Change':-0.18, 'Volume':181800}, {'Symbol':'AIG', 'Price': 71.38, 'Date':'6/11/2007', 'Time':'9:36am', 'Change':-0.15, 'Volume': 195500}, {'Symbol':'AXP', 'Price': 62.58, 'Date':'6/11/2007', 'Time':'9:36am', 'Change':-0.46, 'Volume': 935000}, ] with open('stocks.csv','w') as f: f_csv = csv.DictWriter(f, headers) f_csv.writeheader() f_csv.writerows(rows)