【问题标题】:Using pickle in python to store dictionary在python中使用pickle来存储字典
【发布时间】:2014-07-30 13:32:48
【问题描述】:

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

【问题讨论】:

  • 是的,open('filename.pickle', 'wb') 清除文件 - 您是否希望首先加载字典,修改它们,然后再次存储?
  • 是的,这就是我想要的
  • 为什么不先读取文件,修改后再写回来?

标签: python dictionary pickle


【解决方案1】:

只需使用“追加”模式:

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

=>

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

【讨论】:

  • 虽然通常是添加到文件末尾的正确方法,但使用pickle 会更复杂。然后,您将需要在load 上分别处理多个对象:参见例如stackoverflow.com/a/15463472/3001761
【解决方案2】:

当你打开一个文件时,你需要使用'a'而不是'w'来追加。

reading-and-writing-files

【讨论】:

  • 在为您的答案添加链接时,您应该包含该链接提供的相关信息的摘录。
【解决方案3】:

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

这个怎么样?

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"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-06-28
    • 1970-01-01
    • 2011-06-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-26
    • 1970-01-01
    相关资源
    最近更新 更多