1

I'm new to Python and have stumbled upon a problem while trying to code a program that searches for a line in a csv file containing the put in username.

Code:

# ...
username = input("Please put in username: ")

    with open(r"C:\Users\This\Is\A\Path\user.csv", 'r') as f:
        reader = csv.reader(f, delimiter=',')
        for row in reader:
            if username == row[0]:
                data = row
                print(data)
                line_count += 1
        f.close()
# ...

Error:

Traceback (most recent call last):
  File "C:\Users\This\Is\A\Path\main.py", line 61, in <module>
    if username == row[0]:
IndexError: list index out of range

Contents of user.csv

Username,Name,Age,Gender,Speechproblems,Speechspeed
bingus,Joe,22,m,n,f

My guess is that the datatypes of username and row[0] don't match up, but I wouldn't know how to check what they are because I'm not the brightest tool in the shed. The IDE I'm using is PyCharm using the Python 3.9 Interpreter.

Alexander
  • 13
  • 3
  • 1
    `row` is an empty list (corresponds to a blank line in your file, probably the last line). An empty list does not have the 0th element. – DYZ Nov 05 '21 at 15:36
  • Does this answer your question? [IndexError: list index out of range and python](https://stackoverflow.com/questions/1098643/indexerror-list-index-out-of-range-and-python) – DYZ Nov 05 '21 at 15:38
  • 1
    Thank you DYZ, this was indeed the problem! I fixed it by removing the blank line between the header and the data in the csv file. – Alexander Nov 05 '21 at 15:46
  • 1
    You could also check if `row` is empty, before accessing it: `if len(row) and username == row[0]:` – Marcos Blandim Nov 05 '21 at 15:59

0 Answers0