[英]use pickle to save dictionary in python
我有一個文件hash_db.pickle
,當我創建它時,我在其上保存了一個字典:
v = {hash_value:{"file name":file_name,"file size":file_size,"last scanned time":scanned_time}}
{123dfre345:{"file name":calc.pdf,"file size":234,"last scanned time":12:23 24/12/2013}}
{3gcdshj754:{"file name":star.pdf,"file size":10,"last scanned time":10:30 10/10/2013}}
所以,如果我想從文件中僅更改3gcdshj754
last scanned time
我怎么能這樣做?
你可以使用pickle
。
import pickle
d = pickle.load(open('hash_db.pickle', 'rb'))
d['3gcdshj754']['last scanned time'] = '11:30 11/10/2015'
pickle.dump(d, open('hash_db.pickle', 'wb'))
但是你可能會發現shelve
模塊比直接使用泡菜更方便。 它提供了一個持久的字典,似乎正是你想要的。 樣品用法:
import shelve
from datetime import datetime, timedelta
# create a "shelf"
shelf = shelve.open('hash_db.shelve')
shelf['123dfre345'] = {"file name": 'calc.pdf', "file size": 234, "last scanned time": datetime(2013, 12, 24, 12, 23)}
shelf['3gcdshj754'] = {"file name": 'star.pdf', "file size": 10, "last scanned time": datetime(2013, 10, 10, 10, 30)}
shelf.close()
# open, update and close
shelf = shelve.open('hash_db.shelve')
file_info = shelf['3gcdshj754']
file_info['last scanned time'] += timedelta(hours=+1, minutes=12)
shelf['3gcdshj754'] = file_info
shelf.close()
就是這樣。
使用pickle非常簡單,在寫作時使用
dct = {'3gcdshj754': {'file name': 'star.pdf', 'last scanned time': '10:30 10/10/2014', 'file size': '10'}}
import pickle
pickle.dump(dct, open("save.p", "wb"))
然后,在閱讀時,請使用
import pickle
dct_read = pickle.load(open("save.p", "rb"))
請注意,無論何時,您都必須以二進制模式打開文件( b
標志 )。
現在編輯內容很簡單:
dct_read.values()[0]["last scanned time"] = '10:10 10/10/2010'
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.