[英]How to check if multiple strings are present in a txt file through user input?
我正在嘗試創建一個程序來跟蹤玩家獲勝損失率,現在我正在嘗試讓程序檢查某個名稱是否列在 txt 文件中,但它一直返回為 false。
所以在def check_player
,當我輸入第一個名字時,它說它在列表中,但我輸入的所有后續名字都返回為假。 .txt文件的內容是7個名字,我輸入的名字也是列表中的第一個名字,為什么不檢查整個文件,看名字是否存在?
編輯:我找到了一個更簡單的方法來解決這個問題。 考慮這個關閉
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
我認為您的“返回假”應該減少一個級別,然后刪除其他。 我認為現在的方式, check_player 只看第一行。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.