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}")
Use the syntax import file with file as the Python file containing variables to import the Python file into the current file. To access variables from the other file, use the format file. variable with file as the imported file and variable as the desired variable to return the variable value.
__file__ (A Special variable) in Python A double underscore variable in Python is usually referred to as a dunder. A dunder variable is a variable that Python has defined so that it can use it in a “Special way”. This Special way depends on the variable that is being used.
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()
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. :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With