Reputation:
I have a text file which contains the following
steve:789852:1
sean:1234:1
I want to read the file and is the input from a user matches the first name then print out the middle number. I can do this for one line but not for the rest I keep getting
IndexError: list index out of range
I have tried a for loop and a while loop. The code I am using is below. any help please
x = 0
username = input('enter user name ')
file = open('user_details.txt', 'r')
count = len(open('user_details.txt').readlines())
while x < count:
print(x)
userFile = file.read().split('\n')[x]
userArray = userFile.split(':')
if (userArray[0] == username):
print('password = '+userArray[1])
x = x+1
Upvotes: 0
Views: 1206
Reputation: 3011
readlines()
takes the file pointer to the end of the file. So, when you try to read the file again using the same file reference, an empty string will be returned. Read the contents into a variable and iterate over it in the loop.
Upvotes: 0
Reputation: 21609
loop index variables are not generally needed in python, instead just use a for loop. A good rule of thumb is use a for loop when you know how many iterations there will be and a while when you don't.
username = input('enter user name ')
with open('user_details.txt', 'r') as f:
for line in f:
userArray = line.strip().split(':')
if (userArray[0] == username):
print('password = '+userArray[1])
Note the file is only opened once, and also closed properly using a with
block. It also iterates only the lines of the file themselves once.
The key problem with your code is that you exhaust the file after the first iteration of the while loop.
The intention is to read each line of the file, but what you are doing is counting the lines of the file and looping that many times, then reading the entire file in each of those iterations. The file is not reopened between iterations so the first time the while loop iterates the file is read until the end. When you come round again in the second iteration of the while, there is nothing to read and you attempt to get the 1 index of that empty list, hence the index error.
It works for the first one by accident, because there is a 0th element in the list of all the lines.
Upvotes: 2
Reputation: 2776
Either use
for line in file.readlines():
... do stuff ...
Or use
lines = file.read().split('\n')
for line in lines:
... do stuff ...
Upvotes: 0