试图从我的列表中删除\n,但不断出现错误

2024-04-25 17:37:09 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我终于成功地制作了它,这样我就可以从我的文本文件中读取并将其添加到列表中。但是现在我有一个小问题,每个值看起来像6\n。我需要重新构造我的代码吗。 下面是代码

错误:

Number guessing game with highscores.py", line 42, in <module>
    highscoreS = [highscores.replace("\n", "") for highscores in highscoreS]
NameError: name 'highscoreS' is not defined

尽管我已经清楚地定义了它

from random import randint
a = True
n = randint(1,10)
guesses = 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()


highscores = []
#Compare values and figure out if it is a new highscore
#Maybe I will use the TRY thing got taught recently might help iron out some errors
#f = open("Numbergame.txt").readlines()
with open('Numbergame.txt', 'rt') as f:
    for highscore in f:
        highscores.append(highscore)
        highscoreS = [highscores.replace('\n', '') for highscores in highscoreS]

Tags: the代码intxtforisopenprint
1条回答
网友
1楼 · 发布于 2024-04-25 17:37:09

"Even though I have clearly defined it"

在使用它之前,您需要定义它。到目前为止,highscoreS在定义它的同一行中使用。正确的方法是先将所有值读入列表,然后使用您定义的列表

highscores = []
with open('Numbergame.txt', 'rt') as f:
    for line in f:
        highscores.append(line)

# Notice this is OUTSIDE the loop
highscoreS = [hs.replace('\n', '') for hs in highscores]

要覆盖原始highscores,可以执行以下操作

highscores = [hs.replace('\n', '') for hs in highscores]

然而,这是不必要的复杂。与其这样做,我建议您在阅读分数时只需strip()空格

highscores = []
with open('Numbergame.txt', 'rt') as f:
    for line in f:
        highscores.append(line.strip()) # Or line.replace('\n', '')

您可能还希望将值转换为整数,在这种情况下,在从文件读取行时,在循环中也这样做是有意义的

highscores = []
with open('Numbergame.txt', 'rt') as f:
    for line in f:
        highscores.append(int(line)) # No need to strip because `int()` automatically takes care of that

如@tdelaney所述,您可以将其进一步浓缩为python列表理解:

with open('Numbergame.txt', 'rt') as f:
    highscores = [int(line) for line in f]

相关问题 更多 >