Write variable to file, including name

Is something like this what you're looking for?

def write_vars_to_file(f, **vars):
    for name, val in vars.items():
        f.write("%s = %s\n" % (name, repr(val)))

Usage:

>>> import sys
>>> write_vars_to_file(sys.stdout, dict={'one': 1, 'two': 2})
dict = {'two': 2, 'one': 1}

You can use pickle

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

and to read it again

file = open('dump.txt', 'rb')
data = pickle.load(file)

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


You could do:

import inspect

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

source = inspect.getsourcelines(inspect.getmodule(inspect.stack()[0][0]))[0]
print([x for x in source if x.startswith("mydict = ")])

Also: make sure not to shadow the dict builtin!


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()

Tags:

Python