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

后端 未结 3 1717
灰色年华
灰色年华 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:33

    You can use DictReader too...

    import csv
    
    counter = 1
    
    with open('mock_data.csv', 'r') as csvfile:
        reader = csv.DictReader(csvfile)
        for row in reader:
            filename = "file_%s" % str(counter)
            with open(filename, 'w') as csvfile_out:
            writer = csv.DictWriter(csvfile_out, fieldnames=reader.fieldnames)
            headers = dict((n, n) for n in reader.fieldnames)
            writer.writerow(headers)
            writer.writerow(row)
            counter = counter + 1
    

提交回复
热议问题