File Handling in Python: Open, Read, Write

Module 4 • Session 29 • Allocation: 1 Contact Hr

open() read / write file modes with statement binary files

File handling is a fundamental core concept in software development. Python provides intuitive built-in mechanisms to open, process, and persist data to files stored on your hard drive or network storage.

1. Standard File Modes Overview

The built-in open() function takes a file path and a mode flag to determine read/write access behaviors:

Mode Description Behavior if File Doesn't Exist
'r' Read (default). Opens file for reading text. Raises FileNotFoundError
'w' Write. Overwrites existing contents or creates a new file. Creates a new file
'a' Append. Appends data to the end of the file. Creates a new file
'x' Exclusive creation. Fails if the file exists. Creates a new file
'b' Binary mode. Combined with others (e.g., 'rb', 'wb'). Depends on primary operation

2. Practical File Handling Examples

Example 1: Safe File Reading with with Statement & Error Handling

Using a context manager (with) guarantees proper closing of file descriptors even when errors occur during reading.

file_path = "sample.txt" try: with open(file_path, "r", encoding="utf-8") as file: content = file.read() print("--- File Content ---") print(content) except FileNotFoundError: print(f"Error: The file '{file_path}' was not found.") except PermissionError: print(f"Error: You do not have permission to read '{file_path}'.")

Example 2: Line-by-Line Reading (Memory Efficient for Large Files)

Iterating over a file object directly reads line-by-line using streaming buffers, making it memory-efficient for multi-gigabyte log files.

filename = "server_logs.txt" try: with open(filename, "r", encoding="utf-8") as log_file: for line_number, line in enumerate(log_file, start=1): # strip() removes trailing newlines and whitespace clean_line = line.strip() if "ERROR" in clean_line: print(f"Line {line_number}: {clean_line}") except FileNotFoundError: print("Log file not found. Please create 'server_logs.txt' first.")

Example 3: Writing Multiple Lines (write vs writelines)

Use write() for individual string buffers, or writelines() to stream an iterable list of strings directly into a file.

# Writing individual lines using write() with open("notes.txt", "w", encoding="utf-8") as f: f.write("Header: Meeting Notes\n") f.write("---------------------\n") # Writing a collection of lines using writelines() lines_to_add = [ "1. Discuss quarterly goals\n", "2. Review exception handling practices\n", "3. Assign project tasks\n" ] with open("notes.txt", "a", encoding="utf-8") as f: f.writelines(lines_to_add) print("Notes written successfully.")

Example 4: Binary File Copying (Images, PDFs, Audio)

Non-text files require binary read ('rb') and binary write ('wb') modes to prevent character decoding corruptions.

source_image = "logo.png" destination_image = "logo_backup.png" try: # Read binary ('rb') and write binary ('wb') with open(source_image, "rb") as src, open(destination_image, "wb") as dest: chunk_size = 4096 # Read 4KB chunks while True: chunk = src.read(chunk_size) if not chunk: break dest.write(chunk) print("Image copied successfully.") except FileNotFoundError: print(f"Source file '{source_image}' does not exist.")

Example 5: Exclusive Creation Mode ('x')

Exclusive mode prevents accidental overwrites by throwing a FileExistsError if the target file path already exists.

# Mode 'x' creates a new file, but fails if the file already exists filename = "config_new.json" try: with open(filename, "x", encoding="utf-8") as config_file: config_file.write('{"theme": "dark", "version": "1.0.0"}') print(f"Configuration file '{filename}' created.") except FileExistsError: print(f"Warning: '{filename}' already exists! Operation aborted to prevent overwriting.")
Best Practice: Always explicitly set encoding="utf-8" when opening text files to ensure multi-platform consistency between Windows, macOS, and Linux servers.

🏋️ Try It Yourself: Practice Challenges

Challenge 1: Word Counter Utility

Write a script that creates a file essay.txt, writes three sentences into it, and then reads it back to count the total number of words.

Challenge 2: Log Filter Script

Simulate appending error messages to a log file app.log. Then read the file and copy only lines containing "WARN" into a separate file warnings.log.

Challenge 3: Safe Backup Creator

Write a function that accepts a filename and creates a duplicate backup using exclusive creation mode ('x'), handling existing file exceptions gracefully.

⚡ Interactive Sandbox (File Operations Demo)
Console Output:
Click "Run Code" above to execute file handling script...

📝 Knowledge Check Quiz

1. Which file open mode throws an error if the file already exists?
2. What is the primary benefit of using `with open(...) as file:` context manager?
3. Which modes should be specified to copy a non-text binary file safely?
Advertisement
Horizontal Ad Banner Slot (728x90 / Responsive)