Search code examples
pythonstringsplit

"TypeError: must be str or None, not list" when trying to pass row from csv.reader to str.split


Question:

The 10-th column of this file is 'DeathCity'. For each record in this CSV file, output the record if the city in the DeathCity column matches the user's input. Use upper() to find the match without issues of different capitalization.

import csv

city = input("Enter a city name:")

f = open("/file.txt")
spamreader=csv.reader(f)

for DeathCity in spamreader:
    print("\t".split(DeathCity))

I keep getting an error when attempting to filter the data based on my input.

Traceback (most recent call last):
      File "hmwk3_1", line 7, in <module>
        print("\t".split(DeathCity))
TypeError: must be str or None, not list

Solution

  • If you take a look at the documentation for csv.reader, you will see that you are iterating over rows that are lists of strings. Each element of that list is a column, so use a subscript to access a specific column. That is the string you should compare to the user input.