简体   繁体   中英

Writing a list to a csv file in Python

I am in Python and have a list of numbers that I want to write to a csv file. Say, my list is: [1 2 3 4 5 6 7 8 9], and within the csv file to which I am exporting this data, I want to begin a new line every three numbers. Meaning, when I open my output file in Excel, I want it to look like this.

So, I essentially want to take a 9 element list and write it into a 3x3 matrix. I'm sure I must end up using the writerows command, but have not been able to find documentation of a problem similar enough to mine, so I am not sure exactly what to do with it.

Any help would be greatly appreciated, and I'm sorry if this question has already been asked at some point.

slice your list into a 2D list using a comprehension, and pass that to csv.writerows .

Self-contained example:

import csv

lst = list(range(1,10))

with open("out.csv","w",newline="") as f:
    cw = csv.writer(f)
    cw.writerows(lst[i:i+3] for i in range(0,len(lst),3))

creates a csv file like this:

1,2,3
4,5,6
7,8,9

You can use reshape :

import numpy
my_array=numpy.reshape(my_list, (3,3))

BTW, it should be [1, 2, 3, 4, 5, 6, 7, 8, 9] , not [1 2 3 4 5 6 7 8 9]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM