在python中保存和加载

时间:2018-06-20 16:21:28

标签: python python-3.x loading

我已经四处搜寻,但无法找到针对我特定问题的解决方案。我想做的是获取一个文本文件,其中文件的每一行都包含一个变量。

在我一行一行的文本文件中

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

4 个答案:

答案 0 :(得分:2)

执行此操作可获得结果

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

这将读取每一行并将该行评估为python,而不仅仅是字符串。

答案 1 :(得分:2)

您可以将其放入字典中,并通过键获取值

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'
}

答案 2 :(得分:1)

f = open('your_file_name.txt')
for line in f:
    exec(line)

基本上,您可以使用exec要求Python解释器运行每一行。

答案 3 :(得分:1)

您应该阅读文件,并将其分成几行。将'='处的每一行拆分为值,将所有内容放入字典中,并可能将'....'之外的任何内容解析为整数,将所有其他解析为字符串:

# filename
fn = "file.txt"

# create file
with open(fn,"w") as f: 
    f.write("""name = 'John'
health = 100
gold = 75
currentCell = 'Town'""")

# read file
with open(fn,"r") as f:
    # read all lines, split into lines, string the \n
    t = [x.strip() for x in f.readlines()]

print(t)

输出:

["name = 'John'", 'health = 100', 'gold = 75', "currentCell = 'Town'"]      

然后将其放入字典中:

# create a dictionary from the lines - it will:
#  - for each line split it at = into 2 things
#  - remove whitespaces from each thing
#  - add it into a dictionary, first value as key, second as value
#  - if the second starts with a ' - it will strip the spaces and ' on front and back
#    else it will convert it to an integer 

dictionary = {a.strip(): int(b)    # key : value if condition true
              if not b.strip().startswith("'") 
              else b.strip().strip("'")  # value if condition false
              for a,b in (l.split("=") for l in t if l)}

print(dictionary)

输出:

{'name': 'John', 'health': 100, 'gold': 75, 'currentCell': 'Town'}

您可以使用dictionary['name']访问值以获取'John'

限制:

  • 文件中不能两次输入相同的密钥
  • 文件中不应包含任何空行或w / o =的行,而必须修改代码
  • 到目前为止,它仅能理解stringint,如果您使用其他东西,则需要改编dict-generator-code