0

I'm trying to create a program where I take a user input and see if it is in a specific column (the 10th column) in a CSV file, then print out the entire row in which the input is found. I'm mostly having trouble on the code for matching the string to any values in a column.

city = input("Enter a city name: " ).upper()
with open('file.csv','rt') as file:
        reader = csv.reader(file, delimiter=' ' )
        for row in reader:
                if city == row[9]:
                        print(row)
                else:
                        print(input("City not in file. Enter a city name: "))
                        break

The CSV file looks like:

ID,Date,Age,Sex,Race,City...
1,06/08/2004,32,F,White,Denver
2,06/23/2004,23,M,Black,Hartford
.
.
.

I shortened it so I'm not listing everything, but the city column in the CSV would be the 10th column, not the 6th as above.

Tomerikoo
  • 18,379
  • 16
  • 47
  • 61

1 Answers1

1

It appears that you will exit your for-loop after the first line if there is no match. Try breaking out of the for loop only after you've found a match. If a match isn't found, a message will be printed.

import csv

CITY_NAME_COL = 5

prompt = "Enter a city name: "
found_city = False

with open('cities.csv','rt') as file:
        reader = csv.reader(file)
        next(reader, None)
        city_name = input(prompt)
        while not found_city:
            for row in reader:
                if city_name == row[CITY_NAME_COL]:
                    found_city = True
                    print(row)
                    break
            else:
                    city_name = input(f"City not in file. {prompt}")
                    file.seek(0)

greenBox
  • 552
  • 4
  • 5