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

# Introduction

Writing files is an essential Python skill. This lets you save data permanently instead of losing it when you close the program. 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, add content, work with folders, and save data in CSV and JSON formats. You’ll also learn the most common file modes, including w, a, xAnd rAnd when to use each.

By the end, you’ll 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() Celebration.

w Mode means right 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()

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 the with open(): better way

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

It automatically closes the file after the code block ends. It is clean, safe 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 the with open() This is a best practice because you don’t 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.

Method 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 removing existing content.
x Create a new file. Fails if file already exists.
r Read a file. Fails if 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 change the 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 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())

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

Output:

Write Python code
Run the notebook
Check the output file

One important thing to remember is writelines() Does not automatically add line breaks. you have to include n yourself.

# add to a file

Sometimes you don’t want to replace existing content in a file. Instead, you may want to add new content at 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 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’re working with logs, journals, reports, or any file where you want to add new information.

# Creating files securely

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

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

File created successfully.

If the file already exists, you can check:

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

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

# 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.

mkdir(exist_ok=True) Creates the call folder if it doesn’t already exist. If the folder already exists, Python does not generate any errors.

# writing csv files

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

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

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

Output:

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

newline="" The argument helps avoid extra blank rows 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 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 JSON file:

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

Output:

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

indent=4 The logic makes the JSON file easy to read.

# Common Beginner Mistakes

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

Mistake what happens how to fix it
forgot to close the file Changes could not be saved properly Use with open()
using the w instead of a Existing content is removed Use a while adding
Mistake n Text appears in one line add new line character
write to a missing folder python produces an error Create a folder first
Writing non-string data directly Python can pick up a TypeError Convert values ​​to string or use CSV/JSON

# wrapping up

Writing to files is one of the most useful beginner Python skills. I still remember I joined a programming competition in my second semester of engineering and wasted almost an hour in figuring out how to save a file. If I had known it was that easy, I probably would have won.

File saving helps you store logs, save program output, create reports, hold 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 add new content, and x To safely create a new file without changing an existing file.

abid ali awan (@1Abidaliyawan) 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. Their vision is to create AI products using graph neural networks for students struggling with mental illness.

Related Articles

Leave a Comment