Write variable to file, including name


Question

Let's say I have the following dictionary in a small application.

dict = {'one': 1, 'two': 2}

What if I would like to write the exact code line, with the dict name and all, to a file. Is there a function in python that let me do it? Or do I have to convert it to a string first? Not a problem to convert it, but maybe there is an easier way.

I do not need a way to convert it to a string, that I can do. But if there is a built in function that does this for me, I would like to know.

To make it clear, what I would like to write to the file is:

write_to_file("dict = {'one': 1, 'two': 2}")
1
23
12/14/2009 1:41:27 PM

Accepted Answer

the repr function will return a string which is the exact definition of your dict (except for the order of the element, dicts are unordered in python). unfortunately, i can't tell a way to automatically get a string which represent the variable name.

>>> dict = {'one': 1, 'two': 2}
>>> repr(dict)
"{'two': 2, 'one': 1}"

writing to a file is pretty standard stuff, like any other file write:

f = open( 'file.py', 'w' )
f.write( 'dict = ' + repr(dict) + '\n' )
f.close()
55
12/14/2009 3:20:53 PM

use pickle

import pickle
dict = {'one': 1, 'two': 2}
file = open('dump.txt', 'w')
pickle.dump(dict, file)
file.close()

and to read it again

file = open('dump.txt', 'r')
dict = pickle.load(file)

EDIT: Guess I misread your question, sorry ... but pickle might help all the same. :)


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon