如何使用 python 在 csv 文件中写入和附加循环输出

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.

输出最终的 csv 文件,看起来像,

   0       
   1
   2
   3
   4
   5
   7 
   8
   9

如何有效地做到这一点?

只为每个数字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)))
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 文件。根据我的测试,这实际上会附加到一个已经存在的文件中。

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