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 ?

1

3 Answers 3

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
Sign up to request clarification or add additional context in comments.

Comments

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)

1 Comment

Shouldn't you be using 'a' not 'w'?
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)))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.