Search code examples
pythonexport-to-csv

I am trying to copy a large list to an excel spreadsheet in python


The list has 10,000,000 random numbers in it, and I can't figure out how to get the code to go to the next row when I reach the 16,384 column limit.

Current code:

import csv
import random 
values = []

for i in range(1,10000000):
    
    n = random.randint(0, 1000000)
    values.append(n)
    print(n)

file = open('randresults.csv', 'w')
with file:
    wr = csv.writer(file, dialect = 'excel')
    wr.writerow(values)
file.close()

I tried using wr.writerows(values) but it gives me Error: iterable expected, not float.


Solution

  • After every 16384 values you should write the values array, reset the values array and write it again on the next loop. you need a counter to count the columns

    import csv
    import random 
    values = []
    
    file = open('randresults.csv', 'w')
    
    wr = csv.writer(file, dialect = 'excel')
    col_count = 0
    for i in range(1,10000000):
        col_count = col_count + 1
        n = random.randint(0, 1000000)
        values.append(n)
        if col_count == 16384:
            wr.writerow(values)
            col_count = 0
            values = []
    # write the remaining values, an incomplete row
    wr.writerow(values)
    file.close()