Record csv inside the loop

import csv a=[] with open('large.csv','w') as f1: writer=csv.writer(f1, delimiter='\t',lineterminator='\n',) for i in range(1000000): for j in range(i+1): a.append(i+j*0.2) #print i,j,a #want to write into same csv file??? '''like 0 1 2......999999 0 0.0 1 1.0 1.2 2 2.0 2.2 2.4 . ..... . ..... 999999 ''' a=[] 

I did this in order to avoid the same as twice, and when the list "a" grows, I have to initialize it again (after one iteration of the outer loop). So, I need a list (before initializing it again) written to the csv file as above, but I can’t do it ...... please help.

+6
source share
1 answer

Do you want to do something like this?

 import csv with open('large.csv','w') as f1: writer=csv.writer(f1, delimiter='\t',lineterminator='\n',) for i in range(1000000): row = [i + j*0.2 for j in range(i+1)] writer.writerow(row) 

as well as row / column headers:

 import csv with open('large.csv','w') as f1: writer=csv.writer(f1, delimiter='\t',lineterminator='\n',) writer.writerow([''] + range(1000000)) for i in range(1000000): row = [i] + [i + j*0.2 for j in range(i+1)] writer.writerow(row) 

The latter returns the following file (I replaced 1,000,000 with 10):

  0 1 2 3 4 5 6 7 8 9 0 0.0 1 1.0 1.2 2 2.0 2.2 2.4 3 3.0 3.2 3.4 3.6 4 4.0 4.2 4.4 4.6 4.8 5 5.0 5.2 5.4 5.6 5.8 6.0 6 6.0 6.2 6.4 6.6 6.8 7.0 7.2 7 7.0 7.2 7.4 7.6 7.8 8.0 8.2 8.4 8 8.0 8.2 8.4 8.6 8.8 9.0 9.2 9.4 9.6 9 9.0 9.2 9.4 9.6 9.8 10.0 10.2 10.4 10.6 10.8 
+11
source

Source: https://habr.com/ru/post/901201/


All Articles