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

时间:2019-02-25 14:20:20

标签: python file csv file-io

例如,我想使用循环将元素存储在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

如何有效地做到这一点?

2 个答案:

答案 0 :(得分:0)

只需将每个数字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)))

答案 1 :(得分:0)

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)