我正在编写一个脚本,我需要将CSV读入<div>
<p>Away from keyboard?</p>
<ul class="button">
<li><a href="#0">I'm Back!</a></li>
</ul>
</div>
,对字段执行一些操作(数据重叠),然后通过{{1}将DictReader
输出到csv }。
如果我读了CSV然后写了Dict,那么这个过程就可以了。
DictReader
然而 - 如果我添加一个新列,似乎我丢失了DictReader中的所有数据:
DictWriter
在我写这篇文章之前,有没有办法在DictReader上执行工作?
答案 0 :(得分:3)
由于csvread已被第一个for
循环完全占用,我们的with
语句将输出一个空白文件,您可能会注意到。
你应该:
- &GT;将行保存到变量
import csv
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=',')
rows = []
for row in csvread:
row['NewColumn'] = '1'
rows.append(row)
with open('out.csv', 'w') as out:
headertowrite = ['Time', 'Symbol', 'NewColumn']
writer = csv.DictWriter(out, headertowrite, extrasaction='ignore')
writer.writeheader()
writer.writerows(rows)
或
- &GT;在将输出文件的with语句中进行修改(您读取一行,修改并写入。
import csv
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=',')
with open('out.csv', 'w') as out:
headertowrite = ['Time', 'Symbol', 'NewColumn']
writer = csv.DictWriter(out, headertowrite, extrasaction='ignore')
writer.writeheader()
for row in csvread:
row['NewColumn'] = '1'
writer.writerow(row)
小心!在第二个解决方案中,writerow
不是writerows
!
请注意,我还强烈推荐第二种解决方案,它在内存消耗方面具有更高的可扩展性。