0

I want to store elements in a csv file using loops, for example,

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

The output final csv file with look like,

   0       
   1
   2
   3
   4
   5
   7 
   8
   9

How to do it in efficient way ?

Kallol
  • 2,089
  • 3
  • 18
  • 33
  • Possible duplicate of [How do I read and write CSV files with Python?](https://stackoverflow.com/questions/41585078/how-do-i-read-and-write-csv-files-with-python) – Jab Feb 25 '19 at 14:44

3 Answers3

5

There are some oddities with the code above, notably that "w" option will overwrite the csv file. from my test this would actually append to an already existing file.

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
Flying Turtle
  • 366
  • 7
  • 20
3
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)
roschach
  • 8,390
  • 14
  • 74
  • 124
warwick12
  • 316
  • 3
  • 12
0

Just for each number i write the number to the file:

import csv
with open("filename.csv", 'w') as f:
  writer = csv.writer(f)
  for i in range(10):
      writer.writerow(iter(i))

For your case this could be simply put this way as well.

import csv
with open("filename.csv", 'w') as f:
    writer = csv.writer(f)
    f.writerows(map(str, range(10)))
Jab
  • 26,853
  • 21
  • 75
  • 114