从文本文件读取、修改和写入值

Reading, modifying, and writing values from text file

我目前正在开发 Python 猜数游戏。在我的游戏中,玩家通过尽可能少的猜测来获得“高分”。我打算把那些高分记录在一个文本文件中。

玩家通过比之前的一些高分更少的猜测来完成游戏,从而在高分列表中获得一席之地。我如何修改然后将新的高分列表写入我的“前 10 名”文本文件?下面是程序的代码。

from random import randint
a = True
n = randint(1,10)
guesses = 0
highscores = []
i = 0
beatenscores = 0

#If scores ever need to be reset just run function
def overwritefile():
    f = open("Numbergame.txt", "w")
    f.close()

#overwritefile()
#Guessing Game Code
while a == True:
    guess = int(input("What is your guess? \nEnter a number!"))
    if guess > n:
        print("Guess is too high! \nTry Again!")
        guesses += 1
    elif guess < n:
        print("Guess is too low! \nTry Again!")
        guesses += 1
    else:
        guesses += 1
        a = False

print("You guessed the number! \nIt was " + str(n) + "\nIt took you: " + str(guesses) + " guesses")

#Adding Score to the file
##f = open("Numbergame.txt", "a")
##f.write(str(guesses) + '\n')
##f.close()

# Retrieve the values from the text file and add them to as list, where they can be ints
# Maybe I will use the TRY thing got taught recently might help iron out some errors

with open('Numbergame.txt', 'rt') as f:
    for line in f:
        highscores.append(int(line.strip()))

print(highscores)

# Compare the values from the list and current one
for i in range(len(highscores)):
    if highscores[i] > guesses:
        print(guesses)
        print(highscores[i])
        beatenscores += 1
        i + 1
    else:
        beatenscores += 0

print("You have beaten " + str(beatenscores)+ " scores")

可以从文本文件中读取值,对其进行处理,然后将值写回到文件中。要带走的重要内容是:

  • Python 强大的 with open(...) 系统是从 读取和 写入文件(也称为文件 IO)的规范通用建议
  • 利用条件语句(布尔逻辑)来确定是否以及如何修改数据

如果您想考虑游戏的输出(您指定的 guesses 变量中的用户得分),您需要在写回之前修改您的 highscores 列表变量文件。写入的标准方式与您从文件中读取的方式相同 with open(),但指定写入模式 "w" 而不是读取模式 "r"。作为旁注,您将 "rt" 用于“阅读文本”模式 - "r"“阅读”的默认模式 “阅读文本”模式。有关详细信息,请参阅 this post

以下代码结尾建议的一些注意事项:

  • 您没有指定文本文件中的高分列表是有序的数字列表还是无序列表。无论它是否不是有序的数字列表,下面的建议都应该有效,只要您不关心列表可能随着新的高分添加而变得无序。
  • 使用您当前的术语,“高分”是通过更少的猜测获得的,这有点令人困惑,但可能不值得重构您的代码。
with open('Numbergame.txt', 'rt') as f:
    for line in f:
        highscores.append(int(line.strip()))
print(f"Old high scores: {highscores}")

#Compare the values from the list and current one
for i in range(len(highscores)):
    if highscores[i] > guesses:
        # print(guesses)
        # print(highscores[i])
        beatenscores += 1
        i + 1
    else:
        beatenscores += 0
print("You have beaten " + str(beatenscores)+ " scores")

maxscores = 10
# If a new high score is achieved, replace one of the worst (highest-value)
# scores on the high score list
if beatenscores > 0: 
    # Make room if max number of high scores already recorded
    if len(highscores) > maxscores:
        highscores.pop(highscores.index(max(highscores)))
    # Add new high score
    highscores.append(guesses)

print(f"New high scores: {highscores}")

# Write high score list to file
with open('Numbergame.txt', 'w') as f:
    for score in highscores:
        f.write(f"{score}\n")