繁体   English   中英

在python中使用pickle存储字典

[英]Using pickle in python to store dictionary

我编写了这段代码,用于计算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"

只需使用“追加”模式即可:

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

=>

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

打开文件时,需要使用“ a”代替“ w”。

查看读写文件

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

这个怎么样?

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"

暂无
暂无

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

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