First of all take a look at this answer on reading a file line by line.
How to read a large file, line by line, in Python
The correct, fully Pythonic way to read a file is the following:
with open(...) as f:
for line in f:
# Do something with 'line'
From my understanding, what you are trying to do is to check if the username entered by the user is in the list and than #Do something
.
The first problem is that usernab does not get any value from usernab = print(line.strip())
, as print()
does not return anything. Instead you should assign usernab
the line and than print it:
usernab = line.strip()
print(usernab)
The second problem is that you are trying to use x
witch is a string to iterate in a range of ints. You are basically saying: "For each string in the range 0 to 5, #Do something". You should use another variable.
Furthermore, if (x) in (usernab)
will check if usernab CONTAINS x. Depending on what you want to do, you might want to change this.
This code compiles under Python 3.7. It will add 1
to i
five times, each time x
is found in a line.
f = open("users.txt", "r")
x = str(input("Please enter a valid username: "))
i=0
for line in f:
usernab = line.strip()
print(usernab)
if (x) in (usernab):
for j in range(0,5):
i+=1
print(i)