Table of contents

Python File Handling

File handling is an essential aspect of programming that allows you to read from and write to files. This guide will cover the basics of file handling in Python, including how to open, read, write, and close files. We’ll also explore more advanced topics such as working with different file modes, handling exceptions, and using context managers.

The open() function is used to open a file. It returns a file object, which provides methods and attributes to interact with the file.

Syntax

file_object = open(file_name, mode)
  • file_name: The name of the file to be opened.
  • mode: The mode in which the file is opened (e.g., ‘r’, ‘w’, ‘a’).

Common File Modes

Mode Description
‘r’ Read (default mode)
‘w’ Write (creates a new file or truncates existing)
‘a’ Append (adds to the end of the file)
‘b’ Binary mode (e.g., ‘rb’, ‘wb’)
‘t’ Text mode (default mode, e.g., ‘rt’, ‘wt’)

Example: Opening and Closing a File

# Open a file in read mode file = open("example.txt", "r") # Perform file operations... # Close the file file.close()

Using the with statement ensures that the file is properly closed after its suite finishes, even if an exception is raised. This is the preferred way to work with files.

Example: Using with Statement

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

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

Example

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

The readline() method reads one line at a time, and readlines() reads all lines into a list.

Example: Reading Line by Line

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

Example: Reading All Lines

with open("example.txt", "r") as file: lines = file.readlines() for line in lines: print(line, end="")

The write() method writes a string to the file.

Example

with open("example.txt", "w") as file: file.write("Hello, World!\n") file.write("This is a new line.")

The a mode opens the file for appending, adding new content to the end of the file.

Example

with open("example.txt", "a") as file: file.write("\nThis is an appended line.")

Binary files are used to store data in binary format. You can read and write binary files using the rb and wb modes.

Example: Writing Binary Data

with open("example.bin", "wb") as file: data = bytes([104, 101, 108, 108, 111]) # Equivalent to "hello" in ASCII file.write(data)

Example: Reading Binary Data

with open("example.bin", "rb") as file: data = file.read() print(list(data)) # Output: [104, 101, 108, 108, 111]

It’s important to handle exceptions that may occur during file operations, such as FileNotFoundError or IOError.

Example

try: with open("non_existent_file.txt", "r") as file: content = file.read() except FileNotFoundError: print("File not found.") except IOError: print("An error occurred while reading the file.")

Write a program to copy the content of one file to another.

Example

def copy_file(src, dst): try: with open(src, "r") as source_file: with open(dst, "w") as destination_file: for line in source_file: destination_file.write(line) print(f"File copied from {src} to {dst}") except FileNotFoundError: print(f"The file {src} does not exist.") except IOError as e: print(f"An error occurred: {e}") copy_file("example.txt", "example_copy.txt")

Write a program to count the number of words in a text file.

Example

def count_words(file_name): try: with open(file_name, "r") as file: content = file.read() words = content.split() word_count = len(words) return word_count except FileNotFoundError: print(f"The file {file_name} does not exist.") return 0 word_count = count_words("example.txt") print(f"Number of words: {word_count}")

Write a program to read a file and print each line with a line number.

Example

def print_lines_with_numbers(file_name): try: with open(file_name, "r") as file: for line_number, line in enumerate(file, start=1): print(f"{line_number}: {line}", end="") except FileNotFoundError: print(f"The file {file_name} does not exist.") print_lines_with_numbers("example.txt")

Write a program to merge the content of two files into a third file.

Example

def merge_files(file1, file2, merged_file): try: with open(file1, "r") as f1, open(file2, "r") as f2, open(merged_file, "w") as mf: for line in f1: mf.write(line) for line in f2: mf.write(line) print(f"Files {file1} and {file2} merged into {merged_file}") except FileNotFoundError as e: print(f"File not found: {e.filename}") except IOError as e: print(f"An error occurred: {e}") merge_files("example1.txt", "example2.txt", "merged.txt")

In this guide, we’ve covered the basics of file handling in Python, including opening, reading, writing, and closing files. We’ve also explored more advanced topics such as working with binary files, handling exceptions, and using context managers. File handling is crucial for working with data stored in files, and mastering these concepts will enhance your programming skills. Practice these concepts with the provided examples and exercises to reinforce your understanding. In the next section, we will delve into object-oriented programming (OOP) in Python, which helps you create modular and reusable code. Happy coding!