I am trying to read every line of my file which contains a list of usernames and than make a login system with it. I am trying to implement a basic login system which has usernames stored in a .txt file but my code doesn’t work and I don’t know why. I think that the problem is in my loop which checks for username.
Here is my code but it doesn’t work it just prints fail all the time:
JavaScript
x
25
25
1
a = input('do you have an account y/n:')
2
3
4
if a == 'y':
5
b = input('insert username:')
6
7
file1 = open('file.txt', 'r')
8
lines = file1.readlines()
9
10
for line in lines:
11
if not lines:
12
pass
13
if line == b:
14
print('pass')
15
16
else:
17
print('fail')
18
19
else:
20
d = input('new username:')
21
22
f = open("file.txt", "a")
23
print(d, file=f)
24
f.close()
25
Any ideas?
Advertisement
Answer
JavaScript
1
6
1
for line in lines:
2
if not lines:
3
pass
4
if line == b:
5
print('pass')
6
If the file has any contents, if not lines
will never be true. And since if line == b
is indented underneath that, it never gets executed.
Also, when you iterate over the lines in a file like that, line
will have a newline character at the end, so if line == b
would not be true anyway. You’ll have to strip off the newline character.
Try this instead:
JavaScript
1
4
1
for line in lines:
2
if line.strip() == b:
3
print('pass')
4