【问题标题】:how to write and append loop output in a csv file using python如何使用python在csv文件中写入和附加循环输出
【发布时间】:2019-07-18 23:27:48
【问题描述】:
我想使用循环将元素存储在 csv 文件中,例如,
for i in range(0,10):
#I want to append each i values in new rows of that csv file.
输出的最终 csv 文件看起来像,
0
1
2
3
4
5
7
8
9
如何有效地做到这一点?
【问题讨论】:
标签:
python
file
csv
file-io
【解决方案1】:
只为每个数字i 将数字写入文件:
import csv
with open("filename.csv", 'w') as f:
writer = csv.writer(f)
for i in range(10):
writer.writerow(iter(i))
对于你的情况,这也可以简单地说。
import csv
with open("filename.csv", 'w') as f:
writer = csv.writer(f)
f.writerows(map(str, range(10)))
【解决方案2】:
import csv
with open('loop.csv','w') as f1:
writer=csv.writer(f1, delimiter='\t',lineterminator='\n',)
for i in range(0,10):
row = [i]
writer.writerow(row)
【解决方案3】:
上面的代码有些奇怪,特别是“w”选项会覆盖 csv 文件。从我的测试来看,这实际上会附加到一个已经存在的文件中。
import csv
with open(r'loop.csv','a') as f1: # need "a" and not w to append to a file, if not will overwrite
writer=csv.writer(f1, delimiter='\t',lineterminator='\n',)
# two options here, either:
for i in range(0,10):
row = [i]
writer.writerow(row)
#OR
writer.writerows([i for i in range(10)]) #note that range(0,10) and range(10) are the same thing