Home > Software design >  How to read CSV specific item and add row with this item to the list?
How to read CSV specific item and add row with this item to the list?

Time:10-05

I have csv file:

Type;Manufacturer;Model;Spec;Price
HDD;Seagate;Barracuda;1TB;35,99
HDD;Seagate;Barracuda;2TB;79
HDD;Intenso;;5TB;140
HDD;Fujitsu;;1TB;71,4
HDD;Western Digital;Purple Series;2TB;59
SSD;Western Digital;Blue;500GB;57
SSD;Samsung;970 EVO Plus;500GB;90,99
RAM;Corsair;Vengeance LPX;16GB;99

and I need to find row by specific item and append it to list I tried:

import csv
with open('komponentes.csv') as f:
    elements = [i.split(';')[0] for i in elements] 
    print(elements)
f.close
SDD=[] #SSD and HDD
RAM=[]
GPU=[]
CPU=[]
MB=[]
BP=[]
KRP=[]
for el in elements:
    if el=='SSD':
        SDD.append(elements)
        print(SDD)

but it gives me:

['Veids', 'HDD', 'HDD', 'HDD', 'HDD', 'HDD', 'SSD', 'SSD', 'RAM', 'RAM', 'RAM', 'RAM', 'GPU', 'GPU', 'GPU', 'GPU', 'CPU', 'CPU', 'CPU', 'CPU', 'MB', 'MB', 'MB', 'MB', 'PSU', 'PSU', 'PSU', 'PSU', 'Korpuss', 'Korpuss', 'Korpuss', 'Korpuss', 'Disc', 'Disc']
[['Veids', 'HDD', 'HDD', 'HDD', 'HDD', 'HDD', 'SSD', 'SSD', 'RAM', 'RAM', 'RAM', 'RAM', 'GPU', 'GPU', 'GPU', 'GPU', 'CPU', 'CPU', 'CPU', 'CPU', 'MB', 'MB', 'MB', 'MB', 'PSU', 'PSU', 'PSU', 'PSU', 'Korpuss', 'Korpuss', 'Korpuss', 'Korpuss', 'Disc', 'Disc']]
[['Veids', 'HDD', 'HDD', 'HDD', 'HDD', 'HDD', 'SSD', 'SSD', 'RAM', 'RAM', 'RAM', 'RAM', 'GPU', 'GPU', 'GPU', 'GPU', 'CPU', 'CPU', 'CPU', 'CPU', 'MB', 'MB', 'MB', 'MB', 'PSU', 'PSU', 'PSU', 'PSU', 'Korpuss', 'Korpuss', 'Korpuss', 'Korpuss', 'Disc', 'Disc'], ['Veids', 'HDD', 'HDD', 'HDD', 'HDD', 'HDD', 'SSD', 'SSD', 'RAM', 'RAM', 'RAM', 'RAM', 'GPU', 'GPU', 'GPU', 'GPU', 'CPU', 'CPU', 'CPU', 'CPU', 'MB', 'MB', 'MB', 'MB', 'PSU', 'PSU', 'PSU', 'PSU', 'Korpuss', 'Korpuss', 'Korpuss', 'Korpuss', 'Disc', 'Disc']]

and i need something like:

["SSD;Western Digital;Blue;500GB;57", "HDD;Seagate;Barracuda;2TB;79"]
["RAM;Corsair;Vengeance LPX;16GB;99"]

CodePudding user response:

Use the csv module to parse it. Then compare row[0] with your strings that you use to append to the corresponding lists.

import csv

with open('komponentes.csv') as f:
    csvf = csv.reader(f, sep=';')
    for row in csvf:
        row_string = ';'.join(row)
        if row[0] in ('SDD', 'HDD'):
            SDD.append(row_string)
        elif row[0] == 'RAM':
            RAM.append(row_string)

CodePudding user response:

If you just need something like

["SSD;Western Digital;Blue;500GB;57", "HDD;Seagate;Barracuda;2TB;79"]
["RAM;Corsair;Vengeance LPX;16GB;99"]

Just do

with open('komponentes.csv') as f:
    result = f.readlines()
  • Related