搁置空白清单/字典 [英] Shelve writes blank lists/dictionarys

查看:40
本文介绍了搁置空白清单/字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个API,以在自己制作的游戏上创建自定义地图,但是搁置只是编写空白列表和字典.

I'm trying to make an API to create custom maps on a game I made, but shelve just writes blank lists and dictionarys.

我尝试像这样存储它:显示地图名称的名称""name_1"表示被视为变量的名称纹理的文件路径的纹理"风"代表正在吹的风

I try to store it like that: "name" for the shown name of the map "name_1" for the name that is treated as variable "textures" for the filepath of the texture "wind" for the amount of wind that's blowing

这里是我的代码:

import tkinter.filedialog as tfd
import shelve
import shutil as os

file1 = shelve.open("info")

if "written" in file1:
    pass
else:
    file1["name"] = []
    file1["name_1"] = []
    file1["textures"] = {}
    file1["wind"] = {}
    file1.close()
    file1 = shelve.open("info")

name = input("Name: ")

name1 = input("Name zur Variablenspeicherung: ")

wind = input("Wind (*-*): ")

print("Wähle eine 1200x820 GIF-Datei als Hintergrund aus")
texture = tfd.askopenfilename()
os.copy(texture,"textures/"+texture.split("/")[-1].split("\\")[-1])
texture = "custom/textures/"+texture.split("/")[-1].split("\\")[-1]

print("Schreibe Datei...")

file1["name"].append(name)
file1["name_1"].append(name1)
file1["textures"][name1] = texture
file1["wind"][name1] = [int(wind.split("-")[0]),int(wind.split("-")[1])]
file1["written"] = 1

file1.close()

推荐答案

搁置将在您设置该键时写出对键的更改.它无法检测到值的更改.附加到列表或分配给 value 词典的键将不会被检测到.

shelve will write out changes to keys when you set that key. It can't detect changes to values. Appending to a list or assigning to a key on a dictionary that is value is going to go undetected.

货架文档中:

由于Python的语义,书架不知道何时修改了可变的持久词典条目.默认情况下,仅在将修改后的对象分配到架子时才写入它们(请参见示例).如果可选的 writeback 参数设置为 True ,则所有访问的条目也将缓存在内存中,并写回 sync() close();这样可以更容易地更改持久性词典中的可变条目,但是,如果访问了许多条目,则可能会占用大量内存用于缓存,并且由于所有访问的条目都被写回,因此它会使关闭操作非常慢(无法确定哪些访问项是可变的,哪些实际上是突变的.

Because of Python semantics, a shelf cannot know when a mutable persistent-dictionary entry is modified. By default modified objects are written only when assigned to the shelf (see Example). If the optional writeback parameter is set to True, all entries accessed are also cached in memory, and written back on sync() and close(); this can make it handier to mutate mutable entries in the persistent dictionary, but, if many entries are accessed, it can consume vast amounts of memory for the cache, and it can make the close operation very slow since all accessed entries are written back (there is no way to determine which accessed entries are mutable, nor which ones were actually mutated).

大胆的重点.

writeback 参数设置为 True (并接受不利之处):

Either set the writeback parameter to True (and accept the downsides):

file1 = shelve.open("info", writeback=True)

或明确分配给密钥:

names = file1["name"]
names.append(name)
file1["name"] = names

这篇关于搁置空白清单/字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆