python – csv writing within loop

python – csv writing within loop

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)

or also with the 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 have replaced 1000000 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

python – csv writing within loop

Leave a Reply

Your email address will not be published. Required fields are marked *