How to transform a list into a CSV file with N items per row?

前端 未结 7 950

I want to create a new CSV file with 3 items per row. My source file looks like (there are no new lines / line breaks):

         


        
相关标签:
7条回答
  • 2021-01-29 11:50

    You mentioned:

    My source file looks like (there are no new lines / line breaks):

    12123, 1324, 232324, 243443, 234, 2345 2334, 2445, 22355, 222234, 2345

    So this reads one long row of a CSV, then writes it as groups of three per line:

    import csv
    
    with open('test.csv',newline='') as f:
        reader = csv.reader(f)
        line = next(reader) # Read the one long line
    
    with open('test2.csv', 'w', newline='') as csvfile:
        writer = csv.writer(csvfile)
        for i in range(0,len(line),3): # step by threes.
            writer.writerow(line[i:i+3])
    

    Note that correct use of the csv module requires the files to be opened with newline='' in Python 3 ('rb' or 'wb' in Python 2).

    0 讨论(0)
提交回复
热议问题