[英]Reading files and checking if data is in the file. Python
我正在為一個學校項目制作一個骰子游戲。 當你開始游戲時,你輸入你的名字,它需要從文件“Player_Names.txt”中讀取之前玩過的玩家的名字列表,如果名字不在列表上,那么他們會得到“歡迎”,但如果它他們得到了“歡迎回來”。
使用我當前的代碼會發生什么,它只讀取文件中的第一行,所以如果名稱不在第一行,它將給出一個歡迎新玩家的消息。 另外,如果你的名字的一部分,如果你第一次輸入“馬修”,然后另一次輸入“馬特”它會給你一個“歡迎回來”的消息,但“馬特”是一個不同的人所以它應該是一個“歡迎”的消息。 此外,如果您輸入的名稱在列表中,但在文件的第二行,您沒有得到任何回復程序只是繼續下一行代碼。
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")
我怎樣才能讓程序閱讀所有的行並將整個單詞作為整個單詞處理,而不是像“馬太”這樣的單詞?
你需要讀取所有的行, readline()
你只讀一個...
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")
這里有幾個問題:
if player1 in Names.readline():
print("Welcome back you are player 1")
elif player1 not in Names.readline():
這個結構通常是多余的,因為第一個條件是第二個條件的否定所以你可以寫:
if player1 in Names.readline():
print("Welcome back you are player 1")
else:
但在這種情況下, Names.readline()
具有消耗第一行的副作用。 所以他們不等同。
此外,如果文件中有多行,則算法不起作用。
我會用行創建一個list
並使用any
:
lines = Names.readlines()
if any(player1 in line for line in lines):
# known player
else:
# new player
請注意,您可以使用set
和完全匹配創建更高性能的查找:
lines = {x.strip() for x in Names}
player1 = player1.strip()
if player1 in lines:
....
else:
您需要讀取整個文件並按換行符拆分,這樣您將獲得行列表,匹配將與全名進行比較。 所以第二行應該是
if player1 in Names.read().split('\n'):
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.