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

前端 未结 7 948

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:44

    Here's a solution but it's a bit long. Basically I would write all the values in the csv to a list, then remove three value from the list and write to the csv until there's no values left.

    import csv
    
    # just an example csv
    with open('example.csv', 'w') as csvfile:
        # create example csv with a single row of numbers 0-19
        spamwriter = csv.writer(csvfile)
        spamwriter.writerow([i for i in range(20)])
    
    # open file for reading, append values to list
    l = []
    with open('example.csv') as csvfile:
        # read the example file into a list
        reader = csv.reader(csvfile)
        for row in reader:
            for val in row:
                l.append(val)
    
    
    # write to the original file with 3 values per line
    with open('example.csv', 'w') as csvfile:
        spamwriter = csv.writer(csvfile)
        while l:
            try:
                # write to file 3 values at a time
                spamwriter.writerow(l[:3])
                l = l[3:]
            except:
                # add last bit of file, if file doesn't devide evenly by 3
                spamwriter.writerow(l)
                break
    

    I'd recommend checking out Pandas I find it a lot easier to manipulate csvs with it, but it's not in the standard library.

提交回复
热议问题