简体   繁体   English

使用pickle来保存python中的字典

[英]use pickle to save dictionary in python

I have a file hash_db.pickle that when I created it I saved a dictionary on it: 我有一个文件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}}

so if I want to change from the file only last scanned time for 3gcdshj754 所以,如果我想从文件中仅更改3gcdshj754 last scanned time

how could I do that? 我怎么能这样做?

You can use pickle . 你可以使用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'))

But you might find the shelve module a little more convenient than direct use of pickle. 但是你可能会发现shelve模块比直接使用泡菜更方便。 It provides a persistent dictionary which seems to be exactly what you want. 它提供了一个持久的字典,似乎正是你想要的。 Sample usage: 样品用法:

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

And that's it. 就是这样。

Using pickle is pretty simple, when writing, use 使用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"))

and then, when reading it, use 然后,在阅读时,请使用

import pickle
dct_read = pickle.load(open("save.p", "rb"))

Note that either time, you have to open the file in binary mode ( b flag ). 请注意,无论何时,您都必须以二进制模式打开文件( b标志 )。

Editing the content is now simple: 现在编辑内容很简单:

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

Alternatively, as @mhawke suggests in his answer , you can use shelve . 另外,正如@mhawke在答案中建议的那样,你可以使用搁置

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM