Handling Text Files in Python

File handling enables developers to store, retrieve, and manipulate data. In Python, working with text files is straightforward thanks to its built-in functions and syntax.

This article explores how to handle text files. We’ll cover methods like opening, reading, writing, closing files, deleting, moving, and renaming,

Introduction to File Handling

In a nutshell, file handling involves managing files — creating, reading, updating, and deleting files — to persist data outside the program’s runtime. Python simplifies this process through its built-in open() function and various file modes that determine how files are accessed.

Understanding File Modes in Python

File modes define how a file is accessed and manipulated. Choosing the correct mode is key to ensuring proper interaction with a file. Below are the most commonly used modes:

  • 'r' (Read Mode): Opens a file for reading. The file must exist; otherwise, it raises a FileNotFoundError.
  • 'w' (Write Mode): Opens a file for writing. If the file exists, its content is erased. If it doesn’t exist, a new file is created.
  • 'a' (Append Mode): Opens a file for adding data at the end without affecting existing content.
  • 'x' (Exclusive Creation Mode): Creates a new file. If the file exists, it raises a FileExistsError.
  • 'b' (Binary Mode): Opens the file in binary mode, commonly used for non-text files like images or audio. It can be combined with other modes (e.g., 'rb', 'wb').
  • 't' (Text Mode): Opens the file in text mode by default. This is suitable for text-based files.
  • 'r+' (Read/Write Mode): Opens a file for both reading and writing without erasing existing content.
  • 'w+' (Write/Read Mode): Opens a file for both writing and reading. It clears the content if the file exists or creates a new file.
  • 'a+' (Append/Read Mode): Opens a file for appending and reading. Existing content remains intact.

Handling Files in Python

Opening Files with open()

The open() function is the entry point for interacting with files in Python. Its syntax is:

file = open(file_name, mode)
  • file_name: The name of the file you want to open.
  • mode: Specifies the file access mode ('r', 'w', 'a', etc.).

For example, opening a file in read mode looks like this:

file = open("example.txt", "r")

Reading Files with read() and readline()

Using read(): Reads the entire content of a file as a single string.

with open("example.txt", "r") as file:
    content = file.read()
    print(content)
  • The with statement ensures the file is closed automatically.

Using readline(): Reads a single line at a time.

with open("example.txt", "r") as file:
    line = file.readline()
    print(line)

This method is helpful for processing large files line by line.

Writing to Files with write() and writelines()

Using write(): Writes a string to a file.

with open("example.txt", "w") as file:
    file.write("Hello, Python!")
  • In write mode ('w'), existing content is erased before writing new data.

Using writelines(): Writes multiple lines to a file.

lines = ["First line\n", "Second line\n", "Third line\n"]
with open("example.txt", "w") as file:
    file.writelines(lines)

Difference Between 'w' and 'a'

'w' (Write Mode):

  • Clears the file’s content if it exists.
  • Example:
with open("example.txt", "w") as file:
    file.write("This is a new start.")

'a' (Append Mode):

  • Adds new content to the end of the file without erasing existing data.
  • Example:
with open("example.txt", "a") as file:
    file.write("\nAdding more data.")

Closing Files

While the with statement handles closing automatically, using close() is another way to ensure a file is properly closed:

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

Combining Modes

File modes can be combined for specific use cases:

Binary Read ('rb'): Useful for images and other binary files.

with open("image.png", "rb") as file:
    data = file.read()

Read and Write ('r+'): Allows you to read and write in the same session.

with open("example.txt", "r+") as file:
    file.write("Overwriting initial data.")

Deleting Text Files in Python

To delete a file, Python uses the os or pathlib modules. The os module is more commonly used for its straightforward methods, while pathlib offers a modern, object-oriented approach.

Using the os Module

The os.remove() function deletes a file from the system. Ensure the file exists to avoid errors.

import os

file_path = "example.txt"

if os.path.exists(file_path):
    os.remove(file_path)
    print(f"{file_path} has been deleted.")
else:
    print(f"{file_path} does not exist.")
  • os.path.exists(file_path): Checks if the file exists before attempting deletion.
  • os.remove(file_path): Deletes the file.

Using the pathlib Module

pathlib simplifies file operations with its Path object.

from pathlib import Path

file_path = Path("example.txt")

if file_path.exists():
    file_path.unlink()
    print(f"{file_path} has been deleted.")
else:
    print(f"{file_path} does not exist.")

Moving Text Files in Python

Moving a file involves changing its location within the file system. Python’s shutil module provides a convenient method, shutil.move(), for this purpose.

Using shutil.move()

import shutil

source = "example.txt"
destination = "new_folder/example.txt"

try:
    shutil.move(source, destination)
    print(f"{source} has been moved to {destination}.")
except FileNotFoundError:
    print(f"The source file {source} does not exist.")
  • shutil.move(source, destination): Moves the file from source to destination. It will overwrite the file at the destination if it already exists.
  • The function works for both files and directories.

Renaming Text Files in Python

Renaming a file is another straightforward operation, handled by the os.rename() function or pathlib‘s rename() method.

Using the os.rename() Method

import os

old_name = "example.txt"
new_name = "renamed_example.txt"

if os.path.exists(old_name):
    os.rename(old_name, new_name)
    print(f"File renamed from {old_name} to {new_name}.")
else:
    print(f"{old_name} does not exist.")
  • os.rename(old_name, new_name): Renames the file from old_name to new_name.

Using the pathlib Module

from pathlib import Path

old_name = Path("example.txt")
new_name = old_name.with_name("renamed_example.txt")

if old_name.exists():
    old_name.rename(new_name)
    print(f"File renamed to {new_name}.")
else:
    print(f"{old_name} does not exist.")

Combining Operations: Moving and Renaming Simultaneously

Sometimes, you may want to move and rename a file at the same time. This can be achieved using the shutil.move() function by providing the new name along with the destination.

import shutil

source = "example.txt"
destination = "new_folder/renamed_example.txt"

try:
    shutil.move(source, destination)
    print(f"{source} has been moved and renamed to {destination}.")
except FileNotFoundError:
    print(f"The file {source} does not exist.")

Error Handling in File Management

Errors may occur if the target file or directory doesn’t exist or if permissions are insufficient. To handle these gracefully:

  • Use try and except blocks to catch exceptions like FileNotFoundError and PermissionError.
  • Check if a file exists using os.path.exists() or Path.exists() before performing operations.

Example of error handling:

import os

file_path = "example.txt"

try:
    os.remove(file_path)
    print(f"{file_path} has been deleted.")
except FileNotFoundError:
    print(f"{file_path} does not exist.")
except PermissionError:
    print(f"Permission denied to delete {file_path}.")

informative. If you have any questions, or if you would like to suggest new Python code examples or topics for future tutorials, please feel free to reach out. Your feedback and suggestions are always welcome!

Happy coding!
C. C. Python Programming

You can also find this article at Medium.com

Leave a Reply