So I have finally succeeded in making it so that I can read from my text file and add it to a list. But now I have the slight problem of each value looks like this 6\n. How do I fix this do I need to restructure my code. Below is the code.
The error:
Number guessing game with highscores.py", line 42, in <module>
highscoreS = [highscores.replace("\n", "") for highscores in highscoreS]
NameError: name 'highscoreS' is not defined
Even though I have clearly defined it
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]
CodePudding user response:
"Even though I have clearly defined it"
You need to have defined it before it's used. As of now, highscoreS
is used in the same line that it is defined. The correct way would be to read all values into a list first, and then use the list you defined.
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]
To overwrite the original highscores
, you can do
highscores = [hs.replace('\n', '') for hs in highscores]
However, this is unnecessarily convoluted. Instead of doing it this way, I suggest you simply strip()
the whitespace when you read the score.
highscores = []
with open('Numbergame.txt', 'rt') as f:
for line in f:
highscores.append(line.strip()) # Or line.replace('\n', '')
You also probably want to convert the values to integers, in which case it makes sense to also do that in the loop when you read the lines from the file.
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
You can condense this down even more into a pythonic list comprehension, as @tdelaney mentioned:
with open('Numbergame.txt', 'rt') as f:
highscores = [int(line) for line in f]