使用pickle来保存python中的字典

时间:2014-07-31 07:21:23

标签: python pickle

我有一个文件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}}

因此,如果我只想更改last scanned time

3gcdshj754文件

我怎么能这样做?

2 个答案:

答案 0 :(得分:2)

您可以使用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模块比直接使用pickle更方便。它提供了一个持久的字典,似乎正是你想要的。样品用法:

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()

就是这样。

答案 1 :(得分:1)

使用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 flag)打开文件。

现在编辑内容很简单:

dct_read.values()[0]["last scanned time"] = '10:10 10/10/2010'

或者,正如@mhawke在his answer中建议的那样,您可以使用shelve