简体   繁体   中英

How to split CSV file into 2x separate CSV files based on values

I have a CSV file which contains the dates I worked in a four week period.

The files has two columns [day, month]

26  8
27  8
28  8
29  8
30  8
31  8
1   9
2   9
3   9
4   9
5   9
6   9
7   9

How do I write write this to two new CSV files, which splits on the month end.

I would like the output of CSV_1 to be the following:

26  8
27  8
28  8
29  8
30  8
31  8

I would like the output of CSV_2 to be the following:

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

This should work:

import csv

def write_new_file(data, file_counter):
    with open(f'CSV_{file_counter}.csv', 'w', newline='') as new_csvfile:
        writer = csv.writer(new_csvfile)
        for new_row in new_data:
            writer.writerow(new_row)

with open('csv.csv', newline='') as csvfile:
    data = csv.reader(csvfile)
    new_data = []
    current_month = None
    file_counter = 1
    for row in data:
        if current_month is None:
            current_month = row[1]
        if row[1] != current_month:
            write_new_file(new_data, file_counter)
            current_month = row[1]
            file_counter += 1
            new_data.clear()
        new_data.append(row)
    else:
        write_new_file(new_data, file_counter)

Could probably be a little shorter and sweeter, but it gets the job done. This will also work for CSV files with any number of months, not just 2, just in case.

You may need to change the input file name. Right now I have it set to csv.csv . You could add an input() to manually enter the file name at runtime, instead of hardcoding it.

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