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

Learn how to write, append, and save text, CSV, and JSON files in Python using native file handling tools that work out of the box.



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

Introduction

 
Writing to files is an essential Python skill. It lets you save data permanently instead of losing it when your program stops. You can use file saving to store results, logs, reports, user input, settings, and structured data.

In this guide, you will learn how to create text files, write multiple lines, append content, work with folders, and save data in CSV and JSON formats. You will also learn the most common file modes, including w, a, x, and r, and when to use each one.

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

 

Writing Your First Text File

 
The simplest way to write to a file is to use Python's built-in open() function.

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

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

 

After running this code, Python creates a file named message.txt in the same folder as your notebook or script.

You can read the file back to check what was saved.

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

print(content)

 

Output:

Hello, this is my first file written with Python.

 

Using with open(): The Better Way

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

This automatically closes the file after the code block finishes. It is cleaner, safer, and commonly 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)

 

Output:

This file was written using with open().

 

Using with open() is best practice because you do not need to remember to close the file manually.

 

Understanding File Modes

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

 

Mode Meaning
w Write to a file. Creates a new file or overwrites an existing file.
a Append to a file. Adds content to the end without deleting existing content.
x Create a new file. Fails if the file already exists.
r Read a file. Fails if the file does not exist.

 

For writing files, the most common modes are w and a. Use w when you want to create a new file or replace existing content. Use a when you want to add new content to the end of a file.

 

Writing Multiple Lines

 
You can write multiple lines by adding the newline character \n.

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

 

Read the file:

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

 

Output:

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

 

You can also use writelines() to write a list of strings to a file.

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

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

 

Read the file:

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

 

Output:

Write Python code
Run the notebook
Check the output file

 

One important thing to remember is that writelines() does not automatically add line breaks. You need to include \n yourself.

 

Appending to a File

 
Sometimes you do not want to replace the existing content in a file. Instead, you may want to add new content to the end.

For this, use 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 the file:

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

 

Output:

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

 

Append mode is useful when you are working with logs, journals, reports, or any file where you want to keep adding new information.

 

Creating Files Safely

 
If you want to create a new file but avoid overwriting an existing one, use x mode.

This mode creates a file only if it does not already exist. If the file already exists, Python raises 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 may see:

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

 

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

 

Working with File Paths

 
By default, Python saves files in the same folder where your notebook or script is running.

If you want to save files inside a specific folder, you can use pathlib.

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

 

Output:

File saved to: output/summary.txt

 

Now read the file:

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

 

Output:

This file was saved inside the output folder.

 

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

 

Writing CSV Files

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

To write a CSV file in Python, use the 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())

 

Output:

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

 

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

 

Writing JSON Files

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

To write JSON files in Python, use 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())

 

Output:

{
    "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 Happens How to Fix It
Forgetting to close the file Changes may not be saved properly Use with open()
Using w instead of a Existing content gets deleted Use a when appending
Forgetting \n Text appears on one line Add newline characters
Writing to a missing folder Python raises an error Create the folder first
Writing non-string data directly Python may raise a TypeError Convert values to strings or use CSV/JSON

 

Wrapping Up

 
Writing to files is one of the most useful beginner Python skills. I still remember joining a programming competition in my second semester of engineering and wasting almost an hour trying to figure out how to save a file. If I had known it was this simple, I might have won.

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

For most tasks, use with open() because it automatically closes the file for you. Use w to write or overwrite a file, a to append new content, and x to create a new file safely without replacing an existing one.
 
 

Abid Ali Awan (@1abidaliawan) is a certified data scientist professional who loves building machine learning models. Currently, he is focusing on content creation and writing technical blogs on machine learning and data science technologies. Abid holds a Master's degree in technology management and a bachelor's degree in telecommunication engineering. His vision is to build an AI product using a graph neural network for students struggling with mental illness.


Get the FREE ebook 'KDnuggets Artificial Intelligence Pocket Dictionary' along with the leading newsletter on Data Science, Machine Learning, AI & Analytics straight to your inbox.

By subscribing you accept KDnuggets Privacy Policy


Get the FREE ebook 'KDnuggets Artificial Intelligence Pocket Dictionary' along with the leading newsletter on Data Science, Machine Learning, AI & Analytics straight to your inbox.

By subscribing you accept KDnuggets Privacy Policy

Get the FREE ebook 'KDnuggets Artificial Intelligence Pocket Dictionary' along with the leading newsletter on Data Science, Machine Learning, AI & Analytics straight to your inbox.

By subscribing you accept KDnuggets Privacy Policy

No, thanks!