在python中保存和加载

2024-06-01 09:43:35 发布

您现在位置: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

Tags: 文件tonametxtinputlineopenglobal
3条回答

这样做可以得到你的结果

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

这将读取每一行,并将该行作为python而不仅仅是字符串进行计算。你知道吗

你可以把它放到字典里,然后通过键得到值

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'
}
f = open('your_file_name.txt')
for line in f:
    exec(line)

基本上,您可以使用exec命令Python解释器运行每一行。你知道吗

相关问题 更多 >