Fundamentals 10 min read

Master Python File I/O: Open, Read, Write, and Manage Files Efficiently

This guide walks you through Python's file handling fundamentals—including opening files, reading content, writing data, appending, error handling, and deleting files—so you can manage text and binary files confidently in any project.

Code Mala Tang
Code Mala Tang
Code Mala Tang
Master Python File I/O: Open, Read, Write, and Manage Files Efficiently

In everyday development you often need to store data to files or read information from them, such as building a logging system, parsing configuration files, or saving user input for later use. Mastering Python's file handling techniques can greatly improve efficiency and make many tasks simple and intuitive.

Python File Handling Basics

File handling means operating on files—opening, reading, writing, and closing them. Python makes this process very easy with built‑in functions. Files can be divided into:

Text files : contain readable characters (e.g., .txt, .csv, .html).

Binary files : contain non‑readable data (e.g., images, videos, executables).

To work with a file, Python follows a simple workflow:

Open the file.

Perform read/write operations.

Close the file.

Let's explore these steps in detail.

1. Open a File

First, you need to open the file you want to work with using the open() function.

file = open("example.txt", "r")  # "r" means read mode

When opening a file you must specify two things:

Filename : the name of the file you want to open (e.g., example.txt).

Mode : tells Python what you intend to do with the file.

Common file modes in Python are:

Mode

Description

"r"

Open a file for reading (default). Fails if the file does not exist.

"w"

Open a file for writing. Creates a new file or overwrites existing content.

"a"

Open a file for appending. Adds new content without deleting existing data.

"x"

Open a file for exclusive creation. Fails if the file already exists.

"b"

Open a file in binary mode (for non‑text files such as images, PDFs).

"t"

Open a file in text mode (default for text files).

Example of opening a file in read mode:

file = open("example.txt", "r")
print(file.read())  # read content
file.close()
Tip: Always close a file after use to release system resources.

2. Read Files in Python

After opening a file you can use various Python file methods to read its content: file.read(): reads the entire file as a single string. file.readline(): reads the next line of the file. file.readlines(): returns a list of all lines in the file.

Reading the whole file at once:

file = open("example.txt", "r")
content = file.read()
print(content)  # print entire file content
file.close()

Reading line by line:

file = open("example.txt", "r")
line = file.readline()
print(line)  # print first line
file.close()

Reading all lines as a list:

file = open("example.txt", "r")
lines = file.readlines()
print(lines)  # print list of lines
file.close()

Manually opening and closing files can lead to errors if you forget to close them. To handle this automatically, always use with open():

with open("example.txt", "r") as file:
    content = file.read()
    print(content)  # file is automatically closed

3. Write Files in Python

Python provides different methods to write content, depending on whether you want to overwrite, append, or handle multiple lines.

Using write() to write a single line

The write() method lets you write a string to a file. Note that when used with the "w" mode it overwrites existing content.

with open("example.txt", "w") as file:
    file.write("Hello, World!")  # overwrites existing content

Using writelines() to write multiple lines

If you need to write several lines, use writelines(). It accepts a list of strings and writes them to the file, but does not add newline characters automatically.

lines = ["Line 1
", "Line 2
", "Line 3
"]  # 
 ensures each line is separate
with open("example.txt", "w") as file:
    file.writelines(lines)

Appending data to an existing file

If you do not want to lose the file's existing content, use the "a" (append) mode.

with open("example.txt", "a") as file:
    file.write("
Appending a new line to the file.")

4. Handle Errors in File Operations

One common error when handling files in Python is trying to open a file that does not exist. Opening a non‑existent file in read mode raises a FileNotFoundError.

Here is how to use try and except blocks to handle FileNotFoundError:

try:
    # Attempt to open a non‑existent file
    with open("nonexistent.txt", "r") as file:
        content = file.read()
        print(content)
except FileNotFoundError:
    # Gracefully handle the error
    print("Oops! File not found. Please check the filename and try again.")

Now the program will not display a raw traceback but will inform the user politely.

5. Delete Files in Python

Sometimes you need to delete a file in Python, whether to free space, remove temporary files, or manage outdated data. Python's built‑in os module makes this easy.

import os
os.remove("example.txt")  # delete the file named "example.txt"

Summary: You Have Become a File‑Handling Master!

Congratulations! You have mastered file handling in Python. Now you can confidently open, read, write, and manage files without obstacles.

Quick recap:

Use open() with appropriate mode ("r", "w", "a", etc.).

Use read(), readline(), and readlines() to read files.

Always close files or use with open().

Use write() and writelines() to write data.

Handle errors gracefully with try‑except and FileNotFoundError.

Use the built‑in os module to delete files.

Follow best practices to avoid common pitfalls.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

Pythonfile I/OError Handlingwrite()open()read()
Code Mala Tang
Written by

Code Mala Tang

Read source code together, write articles together, and enjoy spicy hot pot together.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.