How to Save Variables to a File in Python?

In the Python webinar, the topic of discussion was on how to save variables to a file in Python. After experimenting and researching various methods I found several ways to achieve this task. In this article, I will explain how to save variables to file in Python with accurate examples and screenshots of executed example code.

Save Variables to a File in Python

Before getting into saving variables to a file, let’s briefly discuss what variables are in Python. A Python variable is used to store data that can be used later on. By associating a variable with a value, you can refer to the value using a descriptive name and reuse it as many times as needed in your code.

Read How to Read a Specific Line from a Text File in Python?

Save a Single Variable to a Python File

If you need to save a single variable (like a string, integer, or dictionary) to a file in Python, you can use the open() function with write mode ("w"). Here’s a step-by-step example:

# Define a variable
customer_name = "John Smith"

# Specify the file name
filename = "customer.txt"

# Open the file in write mode and save the variable
with open(filename, "w") as file:
    file.write(customer_name)

print(f"Data saved successfully to {filename}")

Output:

Data saved successfully to customer.txt

You can see the output in the screenshot below.

Save Variables to a File in Python

Define the variable customer_name = "John Smith", Specify the file name filename = "customer.txt", Open the file in write mode ("w") This creates the file, Write the variable’s value to the file file.write(customer_name), Automatically close the file after writing. Print confirmation. This helps verify that the process was successful.

Check out How to Import a Class from a File in Python

Save Multiple Variables to a Python File

In many cases, you may need to save multiple variables to a file. Python provides several ways to achieve this. Let’s explore a common approach using string formatting.

Use String Formatting

One way to save multiple variables to a file is by using string formatting. Here’s an example:

name = "Alice Johnson"
age = 28
city = "New York"

filename = "user_info.txt"
with open(filename, "w") as file:
    file.write(f"Name: {name}\nAge: {age}\nCity: {city}")

# Read and print the content to verify
with open(filename, "r") as file:
    content = file.read()
    print(content)

Output:

Name: Alice Johnson
Age: 28
City: New York

You can see the output in the screenshot below.

How to Save Variables to a File in Python

In this example, we define three variables: name, age, and city, each storing different types of information. The filename variable holds the name of the text file where we want to store these values. Using the with open(filename, "w") as file: statement, we open the file in write mode, ensuring that it will be created if it does not exist.

Read How to Copy File and Rename in Python

Write Variables on Separate Lines

Another approach is to write each variable on a separate line in the file.

name = "Michael Brown"
age = 35
city = "Los Angeles"

filename = "user_info.txt"
with open(filename, "w") as file:
    file.write(name + "\n")
    file.write(str(age) + "\n")
    file.write(city + "\n")

In this example, we use the write() method multiple times, writing each variable followed by a line break (\n). Note that we convert the age variable to a string using str() before writing it to the file.

Check out How to Check If a File Exists and Create It If Not in Python?

Save Variables with File Name from User Input

In some scenarios, you may want to save variables to a file with a name provided by the user.

filename = input("Enter the file name: ")
name = "Sarah Davis"
age = 42
city = "Chicago"

with open(filename, "w") as file:
    file.write(f"Name: {name}\nAge: {age}\nCity: {city}")

Here, we prompt the user to enter the desired file name using the input() function. The user-provided file name is stored in the filename variable. Then, we proceed to write the variables to the file using the same approach as before.

Check out How to Get the File Size in MB using Python?

Conclusion

In this tutorial, I discussed how to save variables to a file in Python. I explained how to save a single variable to a Python file, save multiple variables to a Python file, use string formatting, write variables on separate lines, and save variables with file name from user input.

You may like to read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.