繁体   English   中英

如何使用 python 在 csv 文件中编写和 append 循环 output

[英]how to write and append loop output in a csv file using python

我想使用循环将元素存储在 csv 文件中,例如,

  for i in range(0,10):
      #I want to append each i values in new rows of that csv file.

output 最终 csv 文件看起来像,

   0       
   1
   2
   3
   4
   5
   7 
   8
   9

如何以有效的方式做到这一点?

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)

上面的代码有一些奇怪之处,特别是“w”选项将覆盖 csv 文件。 根据我的测试,这实际上是 append 到一个已经存在的文件。

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

对于每个数字, 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)))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM