Open CSV file and writing each row to new, dynamically named CSV file

后端 未结 3 1715
灰色年华
灰色年华 2021-01-23 19:08

I have a csv file with, say, 50 rows of data, and I would like to split it into separate csv files for each row, which includes first row (header) and the the relevant row.

3条回答
  •  时光取名叫无心
    2021-01-23 19:21

    I have tried this and it works fine for your purpose. Unfortunately, I didn't get any csvfile_out error and your with statement works correctly in my Python 2.7.12 console.

    import csv
    
    counter = 1
    
    with open('mock_data.csv', 'r') as csvfile:
        reader = csv.reader(csvfile)
        row1 = next(reader) # here you save your first line of the .csv file
        for row in reader:
            if row: # if row is not empty, write a file with this row
                filename = "file_%s" % str(counter)
                with open(filename, 'w') as csvfile_out:
                    writer = csv.writer(csvfile_out)
                    writer.writerow(row1) #here you write your row1 as first row of csvfile_out
                    writer.writerow(row)
                    counter = counter + 1
    

提交回复
热议问题