首页 > 解决方案 > 在 python 中保存和加载

问题描述

我四处寻找,但无法找到解决我的具体问题的方法。我要做的是获取一个文本文件,其中文件的每一行都包含一个变量。

在文本文件中我有

health == 1099239
gold == 123
otherVar == 'Town'

问题是我无法将它们分成不同的变量,而不仅仅是一个包含所有信息的变量。

目前我将此作为保存到文件中的测试

SaveFileName = input('What would you like to name your save: ')
f = open(SaveFileName + '.txt','w+')
health = input('Health: ')
gold = input('Gold: ')
otherVar = input('Other: ')
otherVar = ("'" + otherVar + "'")
f.write('health == ' + health +'\ngold == ' + gold + '\notherVar == ' + otherVar)
print('done')
f.close()
print('closed')

我的问题不在于保存,因为这似乎完全按预期工作。

这是加载

SaveFileName = input('Save name to load: ')
global health
global gold
global otherVar
health = 100
gold = 1000
otherVar = 'null'
def pause():
    pause = input('Press enter to continue. ')
F = open(SaveFileName + '.txt')
for line in F:
    eval(F.readline())
print(health)
pause()
print(gold)
pause()
print(otherVar)
pause()

当我运行加载文件时,它允许我输入保存文件名,然后在加载时返回

Traceback (most recent call last):
  File "C:/Users/Harper/Dropbox/Python programming/Test area/Load file test.py", line 12, in <module>
    eval(F.readline())
  File "<string>", line 0

    ^
SyntaxError: unexpected EOF while parsing

标签: pythonpython-3.xloading

解决方案


这样做以获得你的结果

F = open(‘file.txt’)
for line in F:
    eval(F.readline())

这将读取每一行并将该行评估为 python 而不仅仅是一个字符串。


推荐阅读