[英]Shelve (or pickle) doesn't save the dict of objects correctly. It just looses the data
我決定為個人需要創建一個跟蹤列表。 我創建了兩個主要的類來存儲和處理數據。 第一個代表主題和練習列表。 第二個代表練習列表中的每個練習(主要是兩個變量,全部(全部)答案和正確(良好)答案)。
class Subject:
def __init__(self, name):
self.name = name
self.exercises = []
def add(self, exc):
self.exercises.append(exc)
# here is also "estimate" and __str__ methods, but they don't matter
class Exercise:
def __init__(self, good=0, whole=20):
self._good = good
self._whole = whole
def modify(self, good, whole=20):
self._good = good
self._whole = whole
# here is also "estimate" and __str__ methods, but they don't matter
我定義了一個詞典,用Subject實例填充它,將其傳輸到擱置文件並保存。
with shelve.open("shelve_classes") as db:
db.update(initiate())
這是表示形式(初始狀態):
#Comma splices & Fused sentences (0.0%)
#0/20 0.0%
#0/20 0.0%
#0/20 0.0%
#0/20 0.0%
#0/20 0.0%
之后,我嘗試重新打開轉儲的文件並更新一些值。
with shelve.open('shelve_classes') as db:
key = 'Comma splices & Fused sentences'
sub = db[key]
sub.exercises[0].modify(18)
db[key] = sub
看起來還不錯,讓我們回顧一下:
print(db[key])
#Comma splices & Fused sentences (18.0%)
#18/20 90.0%
#0/20 0.0%
#0/20 0.0%
#0/20 0.0%
#0/20 0.0%
但是,當我關閉文件時,下次打開它時,它將返回到初始狀態,並且所有更正都會丟失。 甚至用泡菜試過,也不能用。 不知道為什么不保存數據。
shelve
模塊不會在您更改對象時發出通知,只有在您分配它時:
由於Python的語義,貨架無法得知何時修改了可變持久字典條目。 默認情況下,僅在將修改后的對象分配給架子時才寫入它們。
因此無法識別sub.exercises[0].modify(18)
是需要重寫回磁盤的操作。
打開數據庫時,嘗試將writeback
標志設置為True。 然后,它將在關閉時重新保存數據庫,即使它沒有顯式檢測到任何更改。
with shelve.open('shelve_classes', writeback=True) as db:
key = 'Comma splices & Fused sentences'
sub = db[key]
sub.exercises[0].modify(18)
db[key] = sub
您不需要關閉數據庫嗎? 喜歡
db.close()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.