在Python中使用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
当你打开一个文件时,应该用'a'来追加内容,而不是用'w'。
可以查看这个链接了解更多内容:读取和写入文件
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"
1
只需要使用“追加”模式:
with open('filename.pickle', 'wb') as handle:
=>
with open('filename.pickle', 'ab') as handle: