简体   繁体   中英

How to check if multiple strings are present in a txt file through user input?

i am trying to create a program that will keep track of players win loss ratio and right now I am trying to have the program check if a certain name is listed in a txt file or not but it keeps returning as false.

so inside def check_player , when I input the first name it says it is in the list but all subsequent names I enter come back as false. the contents of the .txt file are 7 names, the first name I entered is also the first name on the list, why won't it check the entire file to see if the name is there?

EDIT: I found a much easier method to fix this. Consider this closed

def NewGame():
    
    
    print("how many people are in this game?") 
    people = int(input())
    
    for num in range(people): #does it n times where n is the number of players
        print("who is the Player in this game?")
        player = input()
        file_name = "Player_List.TXT" #initializes the name of the file it is pulled from
        check = check_player(file_name, player) #go to def check_player and pass file & player

        if check == False:
            print("this player is not in the system.")
            print("would you like to add them(Y/N)?: ")
            add = input()
            if add == "Y" or "y":
                AddPlayer()

def check_player(file_name, player): 
    """ Check if any line in the file contains given string """
    # Open the file in read only mode
    with open(file_name, 'r') as read_obj:
        # Read all lines in the file one by one
        for line in read_obj:
            # For each line, check if line contains the string
            if player in line:
                return True
            else:
                return False

I'm thinking your "return False" should be dedented a level, and the else removed. I think the way it is now, check_player is only looking at the first line.

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