Reputation:
I want to know how to write and read variables from a text file. So if I'm doing a game, for example, I'll be able to save the player's progress.
In pseudo code:
variable = 1
# write to text file that variable = 1
# close program
# open program
variable
# Then IDLE should output 1
If you can help me out I would really appreciate it!
Upvotes: 0
Views: 2379
Reputation: 75
To write:
with open('game_vars.txt', 'w') as file:
file.write(f'{score}\n{time}\n{high_score}\n')
To read:
with open('game_vars.txt', 'r') as file:
score = int(file.readline().strip())
time = int(file.readline().strip())
high_score = int(file.readline().strip())
Upvotes: 3