我想知道如何从文本文件中写入和读取变量。因此,例如,如果我在玩游戏,我将能够保存玩家的进度。
使用伪代码:
variable = 1
# write to text file that variable = 1
# close program
# open program
variable
# Then IDLE should output 1
如果您能帮助我,我将不胜感激!
答案 0 :(得分:1)
撰写:
with open('game_vars.txt', 'w') as file:
file.write(f'{score}\n{time}\n{high_score}\n')
阅读:
with open('game_vars.txt', 'r') as file:
score = int(file.readline().strip())
time = int(file.readline().strip())
high_score = int(file.readline().strip())