How to write to files in Python: a beginner’s guide

Share

# Entry

Writing to files is an indispensable Python skill. It allows you to save data permanently instead of losing it when you stop the program. You can utilize file saving to store results, logs, reports, user input, settings, and structured data.

In this guide, you’ll learn how to create text files, write multiple lines, attach content, work with folders, and save data in CSV and JSON formats. You’ll also learn about the most popular file modes, including w, a, xAND rand when to utilize each one.

By the end, you will be able to write Python programs that write results, reports, logs, and structured data to files.

# Saving the first text file

The easiest way to write to a file is to utilize the built-in Python language open() function.

The w mode means recording mode. If the file does not exist, Python creates it. If the file already exists, Python replaces its existing contents.

file = open("message.txt", "w")
file.write("Hello, this is my first file written with Python.")
file.close()

When you run this code, Python creates a file called message.txt in the same folder where the notebook or script is located.

You can re-read the file to see what was written.

file = open("message.txt", "r")
content = file.read()
file.close()

print(content)

Exit:

Hello, this is my first file written with Python.

# Using with open(): A better way

Although you can manually open and close files, the recommended approach is to utilize with open().

This will automatically close the file when the code block ends. It is cleaner, safer, and widely used in real Python projects.

with open("message.txt", "w") as file:
    file.write("This file was written using with open().")

with open("message.txt", "r") as file:
    content = file.read()

print(content)

Exit:

This file was written using with open().

Using with open() this is best practice because you don’t have to remember to close the file manually.

# Understanding file modes

When you open a file, mode tells Python what you want to do with it.

Mode Meaning
w Save to file. Creates a recent file or replaces an existing file.
a Attach to file. Adds content at the end without removing existing content.
x Create a recent file. It will fail if the file already exists.
r Read the file. Failure if file does not exist.

For saving files, the most common modes are w AND a. Employ w when you want to create a recent file or replace existing content. Employ a when you want to add recent content at the end of the file.

# Writing multiple lines

You can write multiple lines by adding a newline character n.

with open("notes.txt", "w") as file:
    file.write("Line 1: Learn Pythonn")
    file.write("Line 2: Practice file handlingn")
    file.write("Line 3: Build small projectsn")

Read file:

with open("notes.txt", "r") as file:
    print(file.read())

Exit:

Line 1: Learn Python
Line 2: Practice file handling
Line 3: Build compact projects

You can also utilize writelines() save a list of strings to a file.

tasks = [
    "Write Python coden",
    "Run the notebookn",
    "Check the output filen"
]

with open("tasks.txt", "w") as file:
    file.writelines(tasks)

Read file:

with open("tasks.txt", "r") as file:
    print(file.read())

Exit:

Write Python code
Run the notebook
Check the output file

There is one essential thing to remember writelines() does not automatically add line breaks. You must include n myself.

# Appending to a file

Sometimes you don’t want to overwrite the existing content of a file. Instead, you can add recent content at the end.

To do this, utilize append mode: a.

with open("journal.txt", "w") as file:
    file.write("Day 1: I started learning Python file handling.n")

with open("journal.txt", "a") as file:
    file.write("Day 2: I learned how to append text to a file.n")

Read file:

with open("journal.txt", "r") as file:
    print(file.read())

Exit:

Day 1: I started learning Python file handling.
Day 2: I learned how to append text to a file.

Append mode is useful when working with logs, logs, reports, or any file to which you want to add recent information.

# Secure file creation

If you want to create a recent file but avoid overwriting the existing one, utilize x mode.

This mode only creates a file if it does not already exist. If the file already exists, Python calls a FileExistsError.

try:
    with open("new_file.txt", "x") as file:
        file.write("This file was created using x mode.")
    print("File created successfully.")
except FileExistsError:
    print("The file already exists, so Python did not overwrite it.")

If the file does not exist, you may see:

File created successfully.

If the file already exists, you can see:

The file already exists, so Python did not overwrite it.

This is useful when you want to protect existing files from being accidentally overwritten.

# Working with file paths

By default, Python saves files to the same folder where your notebook or script runs.

If you want to save files to a specific folder, you can utilize library_path.

from pathlib import Path

output_folder = Path("output")
output_folder.mkdir(exist_ok=True)

file_path = output_folder / "summary.txt"

with open(file_path, "w") as file:
    file.write("This file was saved inside the output folder.")

print(f"File saved to: {file_path}")

Exit:

File saved to: output/summary.txt

Now read the file:

with open("output/summary.txt", "r") as file:
    print(file.read())

Exit:

This file was saved inside the output folder.

The mkdir(exist_ok=True) call creates a folder if it doesn’t already exist. If the folder already exists, Python does not report an error.

# Saving CSV files

CSV files are useful for saving tabular data such as rows and columns. They are commonly opened in spreadsheet tools such as Excel or Google Sheets.

To write a CSV file in Python, utilize the method csv module.

import csv

students = [
    ["Name", "Score"],
    ["Ayesha", 92],
    ["Bilal", 85],
    ["Sara", 88]
]

with open("students.csv", "w", newline="") as file:
    writer = csv.writer(file)
    writer.writerows(students)

Read the CSV file:

with open("students.csv", "r") as file:
    print(file.read())

Exit:

Name,Score
Ayesha,92
Bilal,85
Sara,88

The newline="" The argument helps avoid extra blank lines when saving CSV files, especially on Windows.

# Saving JSON files

JSON is another common format for storing structured data. It is often used for dictionaries, API responses, configuration files, and nested data.

To write JSON files in Python, utilize the json module.

import json

profile = {
    "name": "Ayesha",
    "role": "Data Analyst",
    "skills": ["Python", "SQL", "Excel"],
    "active": True
}

with open("profile.json", "w") as file:
    json.dump(profile, file, indent=4)

Read the JSON file:

with open("profile.json", "r") as file:
    print(file.read())

Exit:

{
    "name": "Ayesha",
    "role": "Data Analyst",
    "skills": [
        "Python",
        "SQL",
        "Excel"
    ],
    "active": true
}

The indent=4 argument makes the JSON file easier to read.

# Common beginner mistakes

Here are some common mistakes beginners make when writing files in Python.

Mistake What’s going on How to fix it
Forgetting to close a file Changes may not be saved correctly Employ with open()
Using w instead a Existing content will be removed Employ a when joining
Forgetfulness n The text appears on one line Add newlines
Writing to the missing folder Python reports an error First create a folder
Directly writing non-string data Python can raise a TypeError Convert values ​​to strings or utilize CSV/JSON

# Summary

Writing to files is one of the most useful Python skills for beginners. I still remember entering a programming competition in my second semester of engineering and wasting almost an hour trying to figure out how to save the file. If I had known it was that plain, I could have won.

File saving helps you store logs, save program output, create reports, store user data, and even read and write plain databases using formats like JSON. The best part is that Python file handling is native, speedy, and works out of the box.

For most tasks, utilize with open() because it automatically closes the file. Employ w save or overwrite the file, a to add recent content and x to safely create a recent file without overwriting the existing one.

Abid Ali Awan (@1abidaliawan) is a certified data science professional who loves building machine learning models. Currently, he focuses on creating content and writing technical blogs about machine learning and data science technologies. Abid holds a Master’s degree in Technology Management and a Bachelor’s degree in Telecommunications Engineering. His vision is to build an AI product using a graph neural network for students struggling with mental illness.

Latest Posts

More News