Home > Net >  How to filter elements starting with “A” from a particular column in csv file?
How to filter elements starting with “A” from a particular column in csv file?

Time:11-29

I'm running this code but having no luck with selecting only the names beginning with "A". I would like to find a solution without using pandas library.

    import csv
    list_a = []

    with open('bl_printed_music_500.csv', newline = '', encoding = 'utf-8-sig') as csvfile:
    reader = csv.DictReader(csvfile)
    
    for row in reader:
       if "A" in row["Composer"]:
       list_a.append(row["Composer"]) 

    print(list_a)

CodePudding user response:

If I understand you correctly, you can use index this way & filter your strings when 'A' is located at index 0

try:
   for row in reader:
       if row["Composer"].index('A') == 0:
           list_a.append(row["Composer"])
except ValueError as e:
    pass
  • Related