Ways to Write Variables to a File in Python

During my ten years of developing Python applications, I have often needed to save data for later use. Whether it is a small configuration setting or a large dataset, knowing how to write variables to a file is a fundamental skill.

In this tutorial, I will show you exactly how I handle file writing in Python. I have used these methods in countless production environments to ensure data is stored safely and efficiently.

Use the basic write() Method

The most direct way I save a string variable to a file is by using the built-in open() function combined with the write() method.

I find this method incredibly useful when I am creating simple logs or saving a single piece of information, like a California real estate property ID.

# Defining a variable with a USA property ID
property_id = "CA-90210-4567"

# Opening a file in write mode ('w')
with open("property_data.txt", "w") as file:
    # Writing the variable to the file
    file.write(property_id)

print("Data successfully written to property_data.txt")

You can refer to the screenshot below to see the output.

python save variable to file

When I use the with statement, Python automatically closes the file for me. This is a practice I highly recommend to avoid memory leaks or file corruption.

1. Write Multiple Variables with writelines()

Sometimes I need to save a list of variables at once, such as a list of major US stock tickers. For this, the writelines() method is my go-to choice.

One thing I learned early on is that writelines() does not add new lines for you. I always make sure to include the \n character if I want each variable on a new row.

# List of US Tech Stock Tickers
stocks = ["AAPL\n", "MSFT\n", "GOOGL\n", "AMZN\n", "TSLA\n"]

# Opening the file to save the list
with open("us_stocks.txt", "w") as file:
    file.writelines(stocks)

print("Stock list saved to us_stocks.txt")

You can refer to the screenshot below to see the output.

python write variable to file

This approach is much cleaner than looping through a list and calling write() repeatedly. It keeps my code concise and professional.

2. Save Variables as JSON Data

In my experience, when I deal with complex data like a user profile containing a name, age, and US state, saving it as a plain string isn’t enough.

I prefer using the json module. It allows me to save dictionaries or lists in a format that remains structured and easy for other applications to read.

import json

# US User Profile Data
user_profile = {
    "name": "James Miller",
    "age": 34,
    "location": "Austin, Texas",
    "is_premium_member": True
}

# Saving the dictionary variable to a JSON file
with open("user_profile.json", "w") as json_file:
    json.dump(user_profile, json_file, indent=4)

print("User profile saved as JSON.")

You can refer to the screenshot below to see the output.

python save variables to file

I always use the indent parameter in json.dump(). It makes the file human-readable, which is a lifesaver when I’m debugging data late at night.

3. Use the Pickle Module for Python Objects

There are times when I need to save a Python variable exactly as it is, including its data type and structure, without converting it to text.

The pickle module is what I use for this. It serializes the object into a binary format. I find this particularly useful for saving machine learning models or complex nested lists.

import pickle

# A list representing quarterly revenue in USD for a startup
quarterly_revenue = [150000, 275000, 310000, 450000]

# Writing the list variable to a binary file
with open("revenue_data.pkl", "wb") as binary_file:
    pickle.dump(quarterly_revenue, binary_file)

print("Revenue data serialized and saved.")

You can refer to the screenshot below to see the output.

save python variable to file

Note that I used “wb” (write binary) mode here. If you try to write a pickle file in standard text mode, the code will throw an error.

4. Append Variables to an Existing File

A common mistake I see junior developers make is overwriting a file when they actually meant to add data to it.

If I am tracking something over time, like daily temperatures in Chicago, I use the “a” (append) mode instead of “w”.

# New temperature reading in Fahrenheit
new_temp_record = "Chicago, IL: 72°F\n"

# Appending the variable to the end of the file
with open("weather_history.txt", "a") as file:
    file.write(new_temp_record)

print("New record added to weather_history.txt")

By using append mode, I ensure that my previous data stays intact while the new variable is tucked neatly at the bottom of the file.

5. Write Variables to a CSV File

If I am preparing data for a spreadsheet, like a list of employees in a New York office, I always opt for the csv module.

This makes it easy for my colleagues to open the resulting file in Excel or Google Sheets without any formatting headaches.

import csv

# US Employee Data: Name, Department, City
employee_data = [
    ["Sarah Connor", "Operations", "New York"],
    ["Michael Scott", "Management", "Scranton"],
    ["Donna Specter", "Legal", "Chicago"]
]

# Writing variables to a CSV file
with open("us_employees.csv", "w", newline='') as csvfile:
    writer = csv.writer(csvfile)
    writer.writerow(["Name", "Department", "City"]) # Header
    writer.writerows(employee_data)

print("Employee data saved to us_employees.csv")

I always include newline=” in the open() function for CSVs. It prevents those annoying extra blank lines that sometimes appear on Windows systems.

In this guide, I have shown you the most reliable ways to save your variables to a file in Python. Whether you need a simple text file, a structured JSON, or a spreadsheet-ready CSV, these methods have served me well over the last decade.

You may also 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.