python-3.x - 尝试将全局变量添加到列表而不是它们的分配
问题描述
该代码是更大程序的一部分。Save 函数保存全局数据(我知道你不应该使用全局变量)并且 Load 函数应该加载它并将全局变量更改为加载的对象。我知道列表只保存分配的对象而不是变量本身,但我不知道如何以不同的方式做到这一点。对于这种情况,有一个解决方案必须改变我保存变量的方式我还将工作保存函数放入代码中。谢谢您的帮助。
我在互联网上搜索了一个解决方案并尝试了一些模块,但无法得到任何工作。
#works
def Save():
global a, b, c, d, e
toSave = [a, b, c, d, e]
count = 0
f = open("file.txt", "w") #file where the vars get saved and should be loaded from
for x in range(len(toSave)):
save = toSave[count]
f.write(str(save)+"\n") #writes the objects the vars are assigned to into a file which each objekt having it's own row
count += 1
tkinter.messagebox.showinfo("Save","Your progress got saved.")
def Load():
global a, b, c, d, e
toLoad = [a, b, c, d, e]
count = 0
f = open("file.txt", "r")
for x in range(len(toLoad)):
toLoad[count] = f.readline() #changes the numbers in the list. Should change the global vars
count += 1
tkinter.messagebox.showinfo("Load","Your progress got loaded.")
我只是想让全局变量成为保存的对象,这样我就可以在我的程序中加载和保存保存文件(这是一个小游戏)。
解决方案
将其全部保存为 JSON 数据,并将其作为字典带回,使用它来加载全局变量。
import json
#works
def Save():
global a, b, c, d, e
save_dict = {
'a': a,
'b': b,
'c': c,
'd': d,
'e': e
}
json_save_data = json.dumps(save_dict)
with open('file.json' mode='w') as file:
file.write(json_save_data)
tkinter.messagebox.showinfo("Save","Your progress got saved.")
def Load():
global a, b, c, d, e
with open('file.json', "r") as file:
data = file.readlines()
global_dict = json.loads(data)
a = global_dict['a']
b = global_dict['b']
c = global_dict['c']
d = global_dict['d']
e = global_dict['e']
tkinter.messagebox.showinfo("Load","Your progress got loaded."
推荐阅读
- python - 一种寻找满足特定条件的主题的熊猫方式
- sql - Apache Phoenix Upsert Into Table Select * from View
- python - 如何在 BeautifulSoup 中获取文本?
- python - Python:一旦找到真值,any() 是否会停止迭代列表/生成器?
- python - 一行中两个函数调用之间的逗号
- python - 如何使用 API 与 Google Colab 交互?
- tsql - 解析 TSQL/Sybase *= 用于使用 ANTLR4 表示外连接的条件运算符
- c# - 大对象的通道和内存管理策略
- assembly - 简单 asm 程序集中的 GET_STRING 不返回字符串
- html - 如何为我的内联 svg spritesheet 图标集向用户添加“安全为 svg”选项