Python File Methods with Examples

When I first started working with Python more than a decade ago, one of the most useful skills I learned was how to work with files.

In this tutorial, I’ll walk you through the most commonly used Python file methods. I’ll share my firsthand experience, along with practical examples that you can try on your own system.

If you’ve ever wondered how to open a file, read its contents, write data, or even check whether a file exists, this guide will help you.

What Are File Methods in Python?

In Python, file methods are built-in functions that allow us to interact with files. Using these methods, we can open files, read data, write new information, update content, and even delete files if needed.

Think of Python file methods as tools in a toolbox. Each method has a specific purpose, and once you know how to use them, handling files becomes second nature.

Open a File in Python

The very first step in working with files is opening them. Python provides the open() function for this purpose.

Here’s a simple example of opening a file in Python.

# Opening a file in Python
file = open("example.txt", "w")
file.write("Hello, this is my first file operation in Python!")
file.close()

In this example, I opened a file named example.txt in write mode. If the file doesn’t exist, Python creates it for me automatically.

Read a File in Python

Once you have a file, the next step is often reading its content. Python provides multiple ways to read files.

Method 1 – Use Python’s read()

The read() method reads the entire file content as a single string.

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

You can see the output in the screenshot below.

python file methods

I often use this method when I need to quickly check what’s inside a file.

Method 2 – Use Python’s readline()

Python’s readline() method reads one line at a time.

# Reading one line at a time
file = open("example.txt", "r")
line = file.readline()
print(line)
file.close()

You can see the output in the screenshot below.

file methods in python

This is useful when I’m working with log files or large text files where I only need specific lines.

Method 3 – Use Python’s readlines()

The readlines() method reads all lines and stores them in a list.

# Reading all lines into a list
file = open("example.txt", "r")
lines = file.readlines()
for line in lines:
    print(line.strip())
file.close()

I prefer this method when I need to process each line separately, like when parsing CSV files.

Write to a File in Python

Writing is just as important as reading. Python makes this easy with the write() and writelines() methods.

Method 1 – Use Python’s write()

The write() method adds a single string to the file.

# Writing a single string
file = open("notes.txt", "w")
file.write("Python is a great language for data analysis in the USA.")
file.close()
print("File created and data written successfully!")

You can see the output in the screenshot below.

file methods python

This is the method I use when I want to save logs or short text notes.

Method 2 – Use Python’s writelines()

The writelines() method writes multiple lines at once.

# Writing multiple lines
lines = [
    "First line of text\n",
    "Second line of text\n",
    "Third line of text\n"
]

file = open("notes.txt", "w")
file.writelines(lines)
file.close()
print("File written successfully!")

You can see the output in the screenshot below.

python file object methods

This is perfect when I already have a list of strings to save into a file.

Append Data to a File

Sometimes, I don’t want to overwrite the existing content. Instead, I want to add new data at the end. For this, I use append mode (a).

# Appending data to an existing file
file = open("notes.txt", "a")
file.write("Adding another line without deleting old content.\n")
file.close()

Appending is useful when keeping logs or updating reports with new information.

Use with open() in Python

One of the best practices in Python is to use the with open() statement. This automatically closes the file, even if an error occurs.

# Using with open for automatic file handling
with open("notes.txt", "r") as file:
    for line in file:
        print(line.strip())

I always use this method in professional projects because it reduces the risk of leaving files open.

Check if a File Exists in Python

Before opening a file, it’s often a good idea to check if it exists. Python provides the os.path and pathlib modules for this.

import os

# Check if a file exists
if os.path.exists("notes.txt"):
    print("The file exists.")
else:
    print("The file does not exist.")

You can see the output in the screenshot below.

file methods

This prevents errors when trying to open non-existent files.

Delete a File in Python

Sometimes, I need to remove a file. Python makes this simple with the os.remove() method.

import os

# Deleting a file
if os.path.exists("old_file.txt"):
    os.remove("old_file.txt")
    print("File deleted successfully.")
else:
    print("File not found.")

I use this when cleaning up temporary files after running scripts.

File Modes in Python

When opening files, Python allows different modes:

  • "r" – Read (default)
  • "w" – Write (creates a new file or overwrites an existing)
  • "a" – Append
  • "b" – Binary mode
  • "x" – Create (fails if file exists)

Example:

# Creating a new file using x mode
try:
    file = open("new_file.txt", "x")
    file.write("This file was created using x mode.")
    file.close()
except FileExistsError:
    print("File already exists.")

These modes give me flexibility depending on what I want to do with the file.

Work with Binary Files in Python

Sometimes I need to handle images or non-text data. For this, I use binary mode (b).

# Writing binary data
with open("binary_file.dat", "wb") as file:
    file.write(b"This is binary data.")

# Reading binary data
with open("binary_file.dat", "rb") as file:
    data = file.read()
    print(data)

Binary mode is essential when dealing with multimedia files or serialized objects.

In this tutorial, I shared my firsthand experience with Python file methods. We explored how to open, read, write, append, and delete files. We also looked at file modes, binary files, and best practices like using open().

If you’re just starting, I recommend practicing these methods with small text files. Once you’re comfortable, you can apply the same techniques to larger and more complex projects.

You may also read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.