在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


江户川乱折腾
浏览 203回答 3
3回答

阿波罗的战车

f = open('your_file_name.txt')for line in f:&nbsp; &nbsp; exec(line)基本上,您可以使用exec ask Python解释器运行每一行。

繁星淼淼

您可以将其放入字典中,并通过键获取值datas = {}with open('demo.txt') as f:&nbsp; &nbsp; for line in f.readlines():&nbsp; &nbsp; &nbsp; &nbsp; key, value = line.split('=')&nbsp; &nbsp; &nbsp; &nbsp; datas[key.strip()] = value.replace("'", '').strip()print(datas)输出{'name': 'John','health': '100','gold': '75','currentCell': 'Town'}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python