python - 在 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
解决方案
这样做以获得你的结果
F = open(‘file.txt’)
for line in F:
eval(F.readline())
这将读取每一行并将该行评估为 python 而不仅仅是一个字符串。
推荐阅读
- react-native - FlatList 中的 TextInput 在屏幕外时失去焦点
- html - 从移动设备切换到桌面时的布局更改(调整大小)
- arrays - 为什么我在将 JSON 解析为 Excel 时收到错误 10001
- c# - switch statement reverting to default regardless of user input?
- r - 使用 modify_url 构建多个 URL
- ballerina - 如何在 Ballerina 中解构/匹配 json 类型?
- python - 无法在python ggplot中对超过9个级别的变量进行刻面
- android - 使用浮点按钮创建菜单项
- javascript - 在不同宽度的可排序 div 中使用 amchart
- php - HTML email is showing as code rather than the css page