在python中使用pickle来存储字典

时间:2014-07-30 13:32:48

标签: python dictionary pickle

我编写了这段代码来计算pdf文件的哈希值并将其添加到字典中并将其保存到这样的文件中:

v={hash_value:{"file name":file_name,"number":1}}

但是下面代码的问题是,如果我添加一个新文件,它会覆盖前一个文件。

f = calculate_hash("calc.pdf")
v = {f:{"file name":"calc.pdf","number":1}}

with open('filename.pickle', 'wb') as handle:
    pickle.dump(v, handle)  

with open('filename.pickle', 'rb') as handle:
    b = pickle.load(handle)

x=  calculate_hash("calc.pdf")
for key in b:
    print key
    if x == key:
        print "yes"

3 个答案:

答案 0 :(得分:1)

只需使用'追加'模式:

with open('filename.pickle', 'wb') as handle:

=>

with open('filename.pickle', 'ab') as handle:

答案 1 :(得分:0)

当您打开文件时,您需要使用' a'追加,而不是' w'

请参阅reading-and-writing-files

答案 2 :(得分:0)

这里的主要错误是您在阅读之前写入文件。从而覆盖所有现有值,而不是将现有值与新值组合。

这个怎么样?

import pickle
import random

def calculate_hash(s):
    return random.randint(1, 100) # not proper hash

f = calculate_hash("calc.pdf")
v = {f:{"file name":"calc.pdf","number":1}}

# read before you write
with open('filename.pickle', 'rb') as handle: # file has to exist here
    b = pickle.load(handle)

# combine the two dictionaries
b = dict(b.items() + v.items())

# write the combined dictionaries
with open('filename.pickle', 'wb') as handle:
    pickle.dump(b, handle)  

x=  calculate_hash("calc.pdf")
for key in b:
    print key
    if x == key:
        print "yes"