Skip to content

Python write variable to file

  • by

In Python, “write variable to file” refers to the process of saving the value of a variable to a file on disk. This is a common operation when you want to store data persistently so that it can be accessed later or shared with other programs or users.

To write a variable to a file in Python, you can follow these steps:

  1. Convert the variable to a string (if it’s not already a string) using the str() function.
  2. Open the file in write mode using the open() function.
  3. Write the string representation of the variable to the file using the write() method.
  4. Close the file to save the changes.

Python write variable to file example

Here’s a simple example of how to write a variable to a file in Python:

# Example variable to write to the file
data = "Hello, World!"

# Specify the file path
file_path = "output.txt"

# Open the file in write mode and write the data to it
with open(file_path, "w") as file:
    file.write(data)

Output:

Python write variable to file

Another example

# Example variable to write to the file
data = {"name": "John", "age": 30, "city": "New York"}

# Convert the variable to a string (using JSON format in this example)
data_str = str(data)

# Specify the file path
file_path = "data.txt"

# Open the file in write mode and write the data to it
with open(file_path, "w") as file:
    file.write(data_str)

In this example, we are using the JSON format to convert the dictionary variable data into a string representation. If your variable is already a string or has a specific format, you can skip the conversion step and directly write it to the file. Just replace data_str with your variable if it’s already a string.

Note: if the file already exists, opening it with "w" mode will overwrite its contents. If you want to append to an existing file or create a new file if it doesn’t exist, you can use "a" mode instead of "w".

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Your email address will not be published. Required fields are marked *