Python用csv写入文件_消除空余行的方法
只做简单地记录,方便一下使用!python关于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
一、csv读入文件消除空余行
import csv #@param: wb:覆盖原来的文件内容 #@param: ab+:追加文件内容 with open('input.csv','wb') as f: f_csv = csv.writer(f) f_csv.writerow(headers) #读入项目标签名 # f_csv.writerows(rows) id = 1 for row in rows: row = list(row) #转换成list,因为原始是tupple row.insert(0,id) #根据特定的题目要求! f_csv.writerow(row) id += 1
二、读取为一个元组的序列
import csv with open('stocks.csv') as f: f_csv = csv.reader(f) headers = next(f_csv) for row in f_csv: # Process row ...
在上面的代码中, row 会是一个列表。因此,为了访问某个字段,你需要使用下标,如 row[0] 访问Symbol, row[4] 访问Change。
三、将数据读取到一个字典序列中
mport csv with open('stocks.csv') as f: f_csv = csv.DictReader(f) for row in f_csv: # process row ...
在这个版本中,你可以使用列名去访问每一行的数据了。比如,row['Symbol'] 或者 row['Change']。
四、写入数据
为了写入CSV数据,你仍然可以使用csv模块,不过这时候先创建一个 writer 对象。例如:
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)
如果你有一个字典序列的数据,可以像这样做:
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)
写入数据最麻烦的问题就是无缘无故的每行数据结束后都会自动多出一个空行的问题。这就是写这篇文章的意义,处理方法就是《一》中的介绍的内容。