Loading a pkl file using dill
Asked Answered
E

1

6

I have a very complex dictionary and dumping, loading directly using dill works. This is in reference to this answer. But there is a slight modification. I need to save this in some file and read that file for later use.

Here's a piece of my code:

NWORDSa is the dictionary that i saved into 'abc.pkl'

pdict1 = dill.dumps(NWORDSa)
dill.dump_session('abc.pkl')

I do not know how to read it back to get the original NWORDSa. I tried:

c = dill.load_session('abc.pkl')
NWORDS_b= dill.loads(c)  

and (wanted to save it in a variable bbn)

with open('abc.pkl', 'rb') as f:
     pickle.dump(bbn, f)  

But both do not work. Is there a better method?

Etsukoetta answered 7/9, 2014 at 7:25 Comment(1)
use .pt for pickle file extension (or at least that's what pycharm highlights which makes me assume that is the common extension).Avelar
C
10

You're dumping the session, not the dictionary itself. I don't know if saving / loading the session is even needed - that depends on your setup.

Try:

with open(outfile, 'wb') as out_strm: 
    dill.dump(datastruct, out_strm)

and:

with open(infile, 'rb') as in_strm:
    datastruct = dill.load(in_strm)

If you need to dump the session, use dill.dump_session('session.pkl') before and dill.load_session('session.pkl') after.

Calchas answered 7/9, 2014 at 18:19 Comment(1)
use .pt for pickle file extension (or at least that's what pycharm highlights which makes me assume that is the common extension).Avelar

© 2022 - 2024 — McMap. All rights reserved.