How to Write Files in Python: A Beginner’s Guide

by ai-intensify
0 comments
How to Write Files in Python: A Beginner's Guide

Writing files is an essential Python skill: it makes it possible to save data permanently instead of losing it when a program closes. It is used to store results, logs, reports, user input, settings, and structured data. This guide covers creating text files, writing multiple lines, appending content, working with folders, and saving data in CSV and JSON, along with the most common file modes (w, a, x, and r) and when to use each. Related on-site material continues in another Python walkthrough.

Writing a first text file

The simplest way to write to a file is Python’s built-in open() function. The w (write) mode creates the file if it does not exist and replaces the contents if it does.

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

The contents can be read back to confirm what was saved:

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

The better way: with open()

Although files can be opened and closed manually, the recommended approach is with open(), which closes the file automatically when the block ends. It is clean, safe, and standard in real projects because there is never a need to remember to close the file by hand.

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)

The two modes used most often are w (to create or replace) and a (to add to the end).

Writing multiple lines

Adding the newline character \n writes multiple lines:

with open("notes.txt", "w") as file:
    file.write("Line 1: Learn Python\n")
    file.write("Line 2: Practice file handling\n")
    file.write("Line 3: Build small projects\n")

A list of strings can also be passed to writelines():

tasks = [
    "Write Python code\n",
    "Run the notebook\n",
    "Check the output file\n"
]

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

Appending instead of overwriting

When existing content should be kept, append mode (a) adds to the end of the file rather than replacing it:

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")

Append mode is ideal for logs, journals, and reports — anywhere information is added over time.

Creating files safely

To create a new file without risking an overwrite, x mode raises a FileExistsError if the file already exists:

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

Working with file paths

By default, Python saves files in the folder where the script runs. To save into a specific folder, pathlib is the cleanest option:

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}")

mkdir(exist_ok=True) creates the folder if it does not already exist and does not raise an error if it does.

Writing CSV files

CSV is useful for saving tabular data. The newline="" argument avoids extra blank rows, especially on Windows:

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)

Writing JSON files

JSON suits structured data such as dictionaries, API responses, configuration, and nested data. The built-in json module handles it:

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)

Common mistakes to avoid

A few errors come up repeatedly. Forgetting to close the file can mean changes are not saved properly, which with open() prevents. Using w instead of a erases existing content, so a is the right choice when adding. Missing the newline character puts everything on one line, so \n matters. Writing to a missing folder raises an error, so the folder must be created first. Writing non-string data directly raises a TypeError, so values should be converted to strings or saved through CSV or JSON.

Wrapping up

Writing to files is one of the most useful beginner Python skills. It stores logs, saves program output, creates reports, holds user data, and reads and writes simple formats such as CSV and JSON. Python’s file handling is native, fast, and works out of the box, and for most tasks with open() is the clean, safe default that handles closing the file automatically.

Related Articles