I have a problem with saving values to file using write(), essentially the program accepts 3 numerical values then stores them as strings in a textfile labeled “scores.txt”. I believe I messed up somewhere in the code itself, since the only thing saved to the textfile is “None” in the place of numbers. Then when the program attempts to read the file it stops with a runtime error. I have searched as best as I can, but maybe I’m not wording it right or something. I have also tried deleting and rewriting the program from scratch twice, but no dice, same problem. My only conclusion, is that I’ve done something incorrectly multiple times in a row, and I still haven’t caught it. This is my first time working with write() & read(), as I continue to learn python, so any help is appreciated. Picture is below (I would put more, but there is a limit):
The code
def main():
write_to_file = open('scores.txt', 'w')
for i in range(3):
score = get_input(0, 100, '\nEnter a score between 0 and 100: ')
write_to_file.write(str(score) + "\n")
write_to_file.close()
#read from a file
read_from_file = open('scores.txt', 'r')
scores = []
for line in read_from_file:
line = line.replace('\n', '')
scores.append(int(line))
read_from_file.close()
print(scores)
print('Average:', sum(scores) / len(scores))
def get_input(min, max, prompt):
while True:
user = int(input(prompt))
if user < min or user > max:
print('Invalid entry. Please re-enter: ')
continue
else:
break
return user
main()
The output:
Enter a score between 0 and 100: 45
Enter a score between 0 and 100: 65
Enter a score between 0 and 100: 76
Traceback:
File "main.py", line 31
main()
File "main.py", line 15, in main
scores.append(int(line))
ValueError: invalid literal for int() with base 10: 'None'
What the savefile should look like:
45
65
76
What the savefile actually looks like:
None
None
None