Splitting rows in csv with comma separated values

I have csv file, which information (id and text) in column’s looks like in example below:

1, Šildomos grindys
2, Šildomos grindys, Rekuperacinė sistema
4, Skalbimo mašina, Su baldais, Šaldytuvas, Šildomos grindys

My desired output is to transfer ID to one row and relate it to its text (it’s for database). Because of csv file is really big, iam giving you just fraction to understand what i want:

| ID             | Features   
| 1              | Šildomos grindys
| 2              | Šildomos grindys
| 2              | Rekuperacinė sistema
| 3              | null
| 4              | Skalbimo mašina
| 4              | Su baldais
| 4              | Šaldytuvas
| 4              | Šildomos grindys

How can i do that via python ? Thanks !

>Solution :

Here is a way to do what you’ve asked:

with open('infoo.txt', 'r', encoding="utf-8") as f:
    records = []
    rows = [[x.strip() for x in row.split(',')] for row in f.readlines()]
    for row in rows:
        for i in range(1, len(row)):
            records.append([row[0], row[i] if row[i] else 'null'])
    with open('outfoo.txt', 'w', encoding="utf-8") as g:
        for record in records:
            g.write(f'{",".join(field for field in record)}\n')

# check the output file:
with open('outfoo.txt', 'r', encoding="utf-8") as f:
    print('contents of output file:')
    [print(row.strip('\n')) for row in f.readlines()]


contents of output file:
1,Šildomos grindys
2,Šildomos grindys
2,Rekuperacinė sistema
4,Skalbimo mašina
4,Su baldais
4,Šildomos grindys

Leave a Reply