Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Split CSV file into multiple files sorted my colum

Hi im a Python noob and i want to make a programm to split my csv file into multiple csv files

the file looks something like this:

main.csv

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Name;Lieferung;Name;Ort;Postleitzahl
somename;60072470;somename;someadress;83620
somename;60071938;somename;someadress;48691
somename;60072194;somename;someadress;13595
somename;60072194;somename;someadress;13595
somename;60072511;somename;someadress;82140

and i want the code to automaticly create multiple csv files grouped by Lieferung:

60072470.csv

somename;60072470;somename;someadress;83620

60071938.csv

somename;60071938;somename;someadress;48691

60072194.csv

somename;60072194;somename;someadress;13595
somename;60072194;somename;someadress;13595

60072511.csv

somename;60072511;somename;someadress;82140

Can someone help me, i did a lot o reaserch but i cant make it 🙁

THX a Lot

>Solution :

import csv

data = {}

with open("a.csv", newline='') as file:
    reader = csv.reader(file, delimiter=';')
    header = next(reader)
    for row in reader:
        data.setdefault(row[1], [])
        data[row[1]].append(row)

for name, row in data.items():
    with open(f"{name}.csv", "w", newline='') as file:
        writer = csv.writer(file, delimiter=';')
        writer.writerow(header)
        writer.writerows(row)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading