我已经四处搜寻,但无法找到针对我的特定问题的解决方案。我正在尝试做的是获取一个文本文件,其中文件的每一行都包含一个变量。在文本文件中一行一行health == 1099239gold == 123otherVar == '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 healthglobal goldglobal otherVarhealth = 100gold = 1000otherVar = '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
3 回答

阿波罗的战车
TA贡献1862条经验 获得超6个赞
f = open('your_file_name.txt')
for line in f:
exec(line)
基本上,您可以使用exec ask Python解释器运行每一行。

繁星淼淼
TA贡献1775条经验 获得超11个赞
您可以将其放入字典中,并通过键获取值
datas = {}
with open('demo.txt') as f:
for line in f.readlines():
key, value = line.split('=')
datas[key.strip()] = value.replace("'", '').strip()
print(datas)
输出
{
'name': 'John',
'health': '100',
'gold': '75',
'currentCell': 'Town'
}
添加回答
举报
0/150
提交
取消