我已經四處搜尋,但無法找到針對我的特定問題的解決方案。我正在嘗試做的是獲取一個文本文件,其中文件的每一行都包含一個變量。在文本文件中一行一行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
提交
取消