Python dict file

I’m in a hurry, but here’s my question… How do I save a dict file? I saved txt files but you can’t save dict files in txts.

I tried pickle but no success.

What are you trying to achieve?

If you are trying to save a dict containing any BPython objects (i.e. anything that is returned by Blender’s Python API), then I’d recommend that you don’t do that, as it is a recipe for disaster as that is very unreliable.

Anyways, if you have a dict called a, a file-object opened for writing called f, then simply do
f.write("%s
" % (repr(a)))

Aligorith

It’s not for blender. When I try to write it prints errors.

I’ll try your version. What’s the %s
for?

The reason why I wrote it like that was for several reasons:

  • the "
    " bit is to add a newline after writing the dict
  • in order to avoid having to make 2 calls to write (which in some cases is not that nice), the “%s” bit is used to substitute the value returned by repr(a) into that string which is then written to the file

how do I load the dict file?

Ok, if you want the data loaded up to a var ‘somedictL’, then when writing the dict to a file (as before), do:

f.write("somedictL = %s
" % (somedictO))

where f is a file-object, and somedictO was the original dict that you were trying to save. Note that I’ve added “somedictL =” to the string that is written. That bit is key to easily loading up the dict again. You’d want to name it the same as the var that you want the dict to live in though (I’ve named them different here for demonstration purposes only) :slight_smile:

Now, to load this back in (assuming that you’ve only got the dict in the file), simply do:

execfile(filename)

where filename is the file that f (above) used. Voila! That’s the beauty of python.

What problems are you having? Did you read the pickle docs? If you are just starting out, I can recommend the O’Reilly Learning python book which briefly covers this topic.

PS. Definitely the wrong part of the forum to post this.

Then where should I of posted it?

I figured it out! Here’s what I did


import pickle
fileimport = file('desiredfilename.pkl', 'w')
pickle.dump(mydictfile, fileimport)
fileimport.close()

You can also use the shelve module, if you want a dict backed by a file.

Martin

My setup does save to a file, and loads from a file.

well, python section maybe?
this is news and chat…

.b