我正在编写一个脚本,我需要将 CSV 读入 a DictReader
,在字段上做一些工作(数据处理),然后DictReader
通过DictWriter
.
如果我阅读 CSV 然后编写字典,则该过程有效。
#Create the sample file
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},
]
#Open sample file
with open('stocks.csv','w') as f:
f_csv = csv.DictWriter(f, headers)
f_csv.writeheader()
f_csv.writerows(rows)
#Output the dict
with open('stocks.csv', 'r') as file:
csvread = csv.DictReader(file, delimiter=',')
with open('out.csv', 'w') as out:
headertowrite = ['Time', 'Symbol', 'NewColumn']
writer = csv.DictWriter(out, headertowrite, extrasaction='ignore')
writer.writeheader()
writer.writerows(csvread)
#Works!
但是 - 如果我添加一个新列,我似乎会丢失 DictReader 中的所有数据:
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)
with open('stocks.csv', 'r') as file:
csvread = csv.DictReader(file, delimiter=',')
for row in csvread:
row['NewColumn'] = '1'
with open('out.csv', 'w') as out:
headertowrite = ['Time', 'Symbol', 'NewColumn']
writer = csv.DictWriter(out, headertowrite, extrasaction='ignore')
writer.writeheader()
writer.writerows(csvread)
#Out.csv is blank!
有没有办法在写之前对 DictReader 执行工作?