Chapter 8: File Handling

File handling in Python allows you to create, read, update, and delete files. It is an essential skill for processing data stored in files such as text files, CSV files, and more.

Opening and Closing Files

To work with a file, you first need to open it. Python provides the open() function to do so. After completing file operations, you should always close the file to release system resources.

Syntax:

file = open("filename", "mode")
# Perform file operations
file.close()

File Modes:

Mode

Description

r

Read (default). Opens the file for reading. Raises an error if the file does not exist.

w

Write. Creates a new file or overwrites an existing file.

a

Append. Adds content to the end of the file.

x

Create. Creates a new file. Raises an error if the file already exists.

t

Text mode (default).

b

Binary mode.

Example:

# Open a file in read mode
file = open("example.txt", "r")
content = file.read()
print(content)
file.close()

Using with Statement:

The with statement is the preferred way to work with files as it automatically closes the file after the block of code is executed.

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

Reading Files

Python provides several methods to read files:

Method

Description

read()

Reads the entire content of the file as a string.

readline()

Reads one line at a time.

readlines()

Reads all lines and returns a list.

Example:

with open("example.txt", "r") as file:
    print(file.read())       # Read entire file
    file.seek(0)             # Move cursor to the beginning
    print(file.readline())   # Read one line
    file.seek(0)
    print(file.readlines())  # Read all lines into a list

Writing to Files

To write content to a file, open it in write (w) or append (a) mode. Writing in w mode overwrites existing content, while a mode adds to the end.

Example:

# Writing to a file
with open("example.txt", "w") as file:
    file.write("Hello, World!\n")
    file.write("Welcome to file handling in Python.\n")

# Appending to a file
with open("example.txt", "a") as file:
    file.write("This is an appended line.\n")

Working with Binary Files

Binary files store data in a non-human-readable format, such as images or videos. Use binary mode (b) to work with these files.

Example:

# Writing binary data
with open("example.bin", "wb") as file:
    file.write(b"\x00\x01\x02\x03")

# Reading binary data
with open("example.bin", "rb") as file:
    content = file.read()
    print(content)  # Output: b'\x00\x01\x02\x03'

File Position and Methods

The file object provides methods to control the file position:

Method

Description

seek(offset)

Moves the cursor to a specific position.

tell()

Returns the current position of the cursor.

Example:

with open("example.txt", "r") as file:
    print(file.tell())  # Output: 0 (start of the file)
    file.read(5)
    print(file.tell())  # Output: 5 (after reading 5 characters)
    file.seek(0)        # Move back to the beginning

Checking File Existence

Use the os module to check if a file exists before performing operations.

Example:

import os

if os.path.exists("example.txt"):
    print("File exists.")
else:
    print("File does not exist.")

Handling Exceptions

Use try...except blocks to handle errors gracefully when working with files.

Example:

try:
    with open("nonexistent.txt", "r") as file:
        content = file.read()
except FileNotFoundError:
    print("File not found.")
except Exception as e:
    print(f"An error occurred: {e}")

Exercises

Exercise 1:

Write a program to read a file and count the number of lines, words, and characters.

Solution:

with open("example.txt", "r") as file:
    content = file.read()
    lines = content.split("\n")
    words = content.split()
    print("Lines:", len(lines))
    print("Words:", len(words))
    print("Characters:", len(content))

Exercise 2:

Write a program to copy content from one file to another.

Solution:

with open("source.txt", "r") as source, open("destination.txt", "w") as dest:
    dest.write(source.read())

Exercise 3:

Write a program to read a binary file and display its contents in hexadecimal format.

Solution:

with open("example.bin", "rb") as file:
    content = file.read()
    print(content.hex())

Best Practices

  1. Always use the with statement to manage files.

  2. Handle exceptions to avoid crashes during file operations.

  3. Use descriptive names for files and variables.

  4. Check if a file exists before performing operations.

  5. Use appropriate file modes to avoid unintended data loss.

In the next chapter, we will explore error and exception handling in greater depth, focusing on best practices for managing runtime errors in Python.

Last updated