Kal*_*lol 0 python csv file-io file
我想使用循环将元素存储在 csv 文件中,例如,
for i in range(0,10):
#I want to append each i values in new rows of that csv file.
Run Code Online (Sandbox Code Playgroud)
输出的最终 csv 文件看起来像,
0
1
2
3
4
5
7
8
9
Run Code Online (Sandbox Code Playgroud)
如何高效地做到这一点?
上面的代码有一些奇怪的地方,特别是“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
Run Code Online (Sandbox Code Playgroud)