user3832061
user3832061

Reputation: 527

Using pickle in python to store dictionary

I wrote this code that calculate the hash value for a pdf file and add it to a dictionary and save it to a file like this:

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

But the problem with the below code is that if I add a new file it overwrite the previous one.

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"

Upvotes: 0

Views: 1636

Answers (3)

Mizipzor
Mizipzor

Reputation: 52341

The main error here is that you write to the file before you read it. Thereby overwriting all existing values rather than combining the existing values with the new one.

How about this?

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"

Upvotes: 0

user1438233
user1438233

Reputation: 1233

when you open a file, you need to use the 'a' for append, instead of 'w'.

see reading-and-writing-files

Upvotes: 0

Evgeny Prokurat
Evgeny Prokurat

Reputation: 734

Just use 'append' mode:

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

=>

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

Upvotes: 1

Related Questions