How to write variable to file in python
Published on Aug. 22, 2023, 12:16 p.m.
To write a variable to a file in Python, you can use the built-in open()
function to create a file object, and then write the variable to the file using the write()
method. Here’s an example:
my_var = {'name': 'John', 'age': 30} # define a variable
with open('output.txt', 'w') as file:
file.write(str(my_var)) # write the variable to the file
In this example, we define a dictionary called my_var
containing some data. We then use a with
statement to create a file object (file
) using the open()
function. We specify the name of the file we want to create ('output.txt'
) and the write mode ('w'
), which means we will be writing to the file.
We then call the write()
method of the file
object to write the contents of the my_var
variable to the file. However, the write()
method only accepts strings as input, so we first convert the variable to a string using the str()
function.
When the with
block is exited, the file is automatically closed, and the changes are saved to disk.
In general, you can use this approach to write any variable (such as a string, a list, a tuple, or a dictionary) to a file in Python. Remember to use the appropriate mode ('w'
for writing, 'a'
for appending) and to convert the variable to a string before writing it to the file using the write()
method.