简体   繁体   中英

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?

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")  

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:

You need to read the whole file and split it by newlines, this way you will get the list of lines and match will compare against full name. So second line should be

if player1 in Names.read().split('\n'):  

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM