To write a variable to a file, you just have to open a file in write mode and use the write() function.
variable = "hello"
with open("example.txt", "w") as f:
f.write(variable)
If you want to add a variable to an existing file and append to the file, then you need to open the file in append mode.
variable = "hello"
with open("example.txt", "a") as f:
f.write(variable)
When working with files in Python, the ability to create new files or modify existing files easily is important.
One such case is if you want to write a variable to a file.
To write a variable to a file, it is easy – you just have to open a file in write mode and use the write() function. write() takes a string and writes it to the file.
Below is a simple example of how you can write a variable to a file using Python.
variable = "hello"
with open("example.txt", "w") as f:
f.write(variable)
If you are trying to write an integer to a file, then you have to convert it to a string with str().
integer = 1
with open("example.txt", "w") as f:
f.write(str(integer))
Append Variable to File Using Python
If you want to append a variable to a file, then you should open the file in append mode.
Below is an example showing you how to append a variable to a file in Python.
variable = "hello"
with open("example.txt", "a") as f:
f.write(variable)
How to Write Multiple Variables to a File Using Python
If you want to write multiple variables to a file using Python, you can build a string and then pass it to write().
For example, if you had multiple variables and wanted to print each one on it’s own line, then you could do the following in Python.
variable1 = "hello"
variable2 = "how are you"
variable3 = "bye"
with open("example.txt", "w") as f:
f.write(variable1 + "\n")
f.write(variable2 + "\n")
f.write(variable3 + "\n")
If you wanted to create a file where the variables were comma delimited, then you could print them all on one line and join them with a comma.
variable1 = "hello"
variable2 = "how are you"
variable3 = "bye"
with open("example.txt", "w") as f:
f.write(",".join([variable1, variable2, variable3]))
Hopefully this article has been useful for you to learn how to write a variable to a file in Python.
Leave a Reply