Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Write variable to file, including name

Tags:

python

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}")
like image 599
Orjanp Avatar asked Dec 14 '09 13:12

Orjanp


People also ask

How do you assign a variable to a text file in Python?

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.

What does __ file __ mean in Python?

__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.


2 Answers

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()
like image 129
Adrien Plisson Avatar answered Sep 28 '22 14:09

Adrien Plisson


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. :)

like image 31
Johannes Charra Avatar answered Sep 28 '22 16:09

Johannes Charra