Reputation: 11
I'm trying to check a file to test if there's a variable in it, but it only seems to believe the variable isn't in the file, even when it is.
I'm trying to check for player1
in the file, LOGINS.txt
, and the part where it writes player1
to the file appears to work, but it only seems to return that player1
is not in the file, even when it is. I have tried printing the reading of the file, but it prints a blank line.
D = False
# ^ Main Loop
Q = False
# ^ Sub-loops
while D != True:
player1 = input("What is Player 1's name?\n")
with open("LOGINS.txt", "a+") as f:
w = f.read()
if player1 in w:
print("Authorised")
else:
un_player1 = input("Not currently authorised, would you like to add your name to the list? Y/N.\n")
while Q != True:
if un_player1 == "Y":
f.writelines(str(player1) + "\n")
print("Registered.")
Q = True
else:
print("Bye!")
Q = True
D = True
I didn't close the file at the end because I'm planning to use the opened file for a piece of code straight after.
Thank you everyone for helping me! It's working now and I'm very grateful
Upvotes: 1
Views: 54
Reputation: 66
On the line
with open("LOGINS.txt", "a+") as f:
your using "a+" mode for your file reader. As Mahrkeenerh pointed out this places your pointer at the end of the file, so when you go to read, the string is empty and you get False.
Mahrkeenerh just beat me with his comment, but the solution to this is using f.seek(0) to move your pointer back to the start of the file, or if you know where the variable your looking for is you can set it to that point.
Upvotes: 1