Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading files and checking if data is in the file. Python

I'm making a dice game for a school project. When you start the game you input your name and it need to read from the file "Player_Names.txt" the list of names of players who played before if the name isn't on the list then they get a "welcome" but if it is they get a "welcome back".

With my current code what happens is it only reads the 1st line in the file so if the name isn't on the 1st line it'll give back a message for welcoming a new player. Also if its part of a name so if you first enter "Matthew" and then another time enter "Matt" it will give you a "welcome back" message but "Matt" is a different person so it should be a "welcome" message. Also if the Name you enter is on the list but on the 2nd line in the file you get nothing back the program just continues to the next line of code.

Names = open("Player_Names.txt", "r+")  
player1 = input("Enter your name: ")  
if player1 in Names.readline():  
    print("Welcome back you are player 1")  
elif player1 not in Names.readline():  
    print("Welcome you are player 1")  
    Names.write(player1)  
    Names.write("\n")  

How can I get the programe to read all the lines and treat the words inputed as whole words not letters like in the "Matthew" example?

like image 437
XTG_YOLO Avatar asked May 14 '26 17:05

XTG_YOLO


2 Answers

Several issues here:

if player1 in Names.readline():  
    print("Welcome back you are player 1")  
elif player1 not in Names.readline():  

this construct is normally redundant, because first condition is the negation of the second so you could write:

if player1 in Names.readline():  
    print("Welcome back you are player 1")  
else:

but in that case Names.readline() has the side effect of consuming the first line. So they're not equivalent.

Besides, if you have several lines in your file, your algorithm doesn't work.

I would create a list with the lines and use any:

lines = Names.readlines()
if any(player1 in line for line in lines):
   # known player
else:
   # new player

note that you can create a more performant lookup using a set and exact match:

lines = {x.strip() for x in Names}
player1 = player1.strip()
if player1 in lines:
   ....
else:
like image 65
Jean-François Fabre Avatar answered May 16 '26 05:05

Jean-François Fabre


You need to read all the lines, with readline() you're reading just one...

Names = open("Player_Names.txt", "r+")  
content = Names.readlines()

content = [x.strip() for x in content] 

if player1 in content:  
    print("Welcome back you are player 1")  
else: 
    print("Welcome you are player 1")  
    Names.write(player1)  
    Names.write("\n")  
like image 28
Lucas Hort Avatar answered May 16 '26 05:05

Lucas Hort