我试图使用搁置来保存/加载文件中的某些数据。我有一个词典列表:
inv = [slot0, slot1, slot2, slot3, slot4, slot5, slot6]
7个词典中的每一个都是这样的,但值略有不同:
slot0 = {"item_pos": [hud_x + 592, hud_y + 4], "text_pos": [hud_x + 612, hud_y + 25], "item": None, "amount": 0}
为了保存/加载字典,我使用"搁置"模块,这是保存的代码:
with shelve.open((os.path.join(saves_path, "inventory", "inventory")), "c") as f:
f["slot0_item"] = slot0["item"]
f["slot0_amount"] = slot0["amount"]
f["slot1_item"] = slot1["item"]
f["slot1_amount"] = slot1["amount"]
f["slot2_item"] = slot2["item"]
f["slot2_amount"] = slot2["amount"]
f["slot3_item"] = slot3["item"]
f["slot3_amount"] = slot3["amount"]
f["slot4_item"] = slot4["item"]
f["slot4_amount"] = slot4["amount"]
f["slot5_item"] = slot5["item"]
f["slot5_amount"] = slot5["amount"]
f["slot6_item"] = slot6["item"]
f["slot6_amount"] = slot6["amount"]
以下是加载代码:
with shelve.open((os.path.join(saves_path, "inventory", "inventory")), "c") as f:
slot0["item"] = f["slot0_item"]
slot0["amount"] = f["slot0_amount"]
slot1["item"] = f["slot1_item"]
slot1["amount"] = f["slot1_amount"]
slot2["item"] = f["slot2_item"]
slot2["amount"] = f["slot2_amount"]
slot3["item"] = f["slot3_item"]
slot3["amount"] = f["slot3_amount"]
slot4["item"] = f["slot4_item"]
slot4["amount"] = f["slot4_amount"]
slot5["item"] = f["slot5_item"]
slot5["amount"] = f["slot5_amount"]
slot6["item"] = f["slot6_item"]
slot6["amount"] = f["slot6_amount"]
虽然这段代码运行良好,但它很长且效率很低。我尝试使用" for"循环以保存这样的数据:
for slot in inv:
f["slot_item"] = slot["item"]
f["slot_amount"] = slot["amount"]
...并加载如下数据:
for slot in inv:
slot["item"] = f["slot_item"]
slot["amount"] = f["slot_amount"]
然而,当我使用这种方法时,字典不会在重新启动程序时保存/加载他们的更改,就像他们应该的那样。我怎样才能(如果可能的话)正确使用" for"循环以有效地保存/加载搁置的数据?
编辑:hud_x
和hud_y
都等于20
答案 0 :(得分:0)
如果您可以设法使用dictinary或列表而不是slot1
,slot2
等代码可以更容易。
import json
from pathlib import Path
import random
# repliacting some data
def generate_dict():
return {"item_pos": [rnd() + 592, rnd() + 4],
"text_pos": [rnd() + 612, rnd() + 25],
"item": None,
"amount": 0}
def rnd():
return random.randint(0, 1000)
# change of data structure
dict_list = [generate_dict() for id in range(7)]
# easily seriliasable into json
json_str = json.dumps(dict_list, sort_keys=True, indent=4)
# you can save json as file
Path('store.json').write_text(json_str)
# read back
assert json.loads(Path('store.json').read_text()) == dict_list
答案 1 :(得分:0)
我决定使用泡菜,因为它更容易使用"对于"循环。此外,搁置使用类似字典的语法(pickle不会),因此这可能是问题的一部分。
保存:
with open((os.path.join(saves_path, "inventory", "inventory.txt")), "wb") as f:
for slot in inv:
pickle.dump(slot["item"], f)
pickle.dump(slot["amount"], f)
装载:
with open((os.path.join(saves_path, "inventory", "inventory.txt")), "rb") as f:
for slot in self.inventory.inv:
slot["item"] = pickle.load(f)
slot["amount"] = pickle.load(f)