Python Chapter 7: File Handling

Master file operations, data persistence, and exception handling

File Handling Basics

Opening Files - The open() Function

The open() function is used to open files in Python. It returns a file object.

# Basic syntax file = open('filename.txt', 'mode')
Important: Always close files after use with file.close() or use the with statement for automatic closing.

Reading Methods

read()

Reads entire file content as a single string.

with open('file.txt', 'r') as f: content = f.read() print(content)

readline()

Reads a single line from the file.

with open('file.txt', 'r') as f: line = f.readline() print(line)

readlines()

Reads all lines and returns them as a list.

with open('file.txt', 'r') as f: lines = f.readlines() for line in lines: print(line)

Iterating Lines

Loop through file line by line (memory efficient).

with open('file.txt', 'r') as f: for line in f: print(line.strip())

Writing Methods

write()

Writes a string to the file.

with open('file.txt', 'w') as f: f.write('Hello World\n')

writelines()

Writes a list of strings to the file.

lines = ['Line 1\n', 'Line 2\n'] with open('file.txt', 'w') as f: f.writelines(lines)

The with Statement

Best Practice: The with statement automatically closes the file, even if an exception occurs. It's the recommended way to work with files.
# Without 'with' - must manually close file = open('file.txt', 'r') content = file.read() file.close() # Must remember to close! # With 'with' - automatically closes with open('file.txt', 'r') as file: content = file.read() # File automatically closed here

File Modes Comparison

Mode Description Creates File Position Truncates
'r' Read only (default) No (error if missing) Beginning No
'w' Write only Yes Beginning Yes
'a' Append only Yes End No
'r+' Read and Write No (error if missing) Beginning No
'w+' Read and Write Yes Beginning Yes
'a+' Read and Append Yes End No
'b' Binary mode (add to any mode) Depends on base mode Depends on base mode Depends on base mode

Interactive Mode Demonstrator

Detailed Mode Explanations

'r' - Read Mode

Opens file for reading. File must exist.

with open('data.txt', 'r') as f: content = f.read() # FileNotFoundError if file doesn't exist

'w' - Write Mode

Creates new file or overwrites existing file.

with open('data.txt', 'w') as f: f.write('New content') # WARNING: Erases all existing content!

'a' - Append Mode

Adds content to end of file. Creates if doesn't exist.

with open('log.txt', 'a') as f: f.write('New log entry\n') # Preserves existing content

'rb' - Binary Read

Reads binary files (images, videos, etc.).

with open('image.png', 'rb') as f: binary_data = f.read() # Returns bytes object

Interactive Code Simulator

Watch how file operations execute step by step

Python Code

File Contents & Output

Virtual File System

Practice file operations in your browser

Create/Write File

Read File

Your Files

    Operation Log

    File Paths & OS Module

    Path Types

    Absolute Path

    Complete path from root directory

    # Windows 'C:\\Users\\John\\Documents\\file.txt' # Linux/Mac '/home/john/documents/file.txt'

    Relative Path

    Path relative to current directory

    # Same directory 'file.txt' # Subdirectory 'data/file.txt' # Parent directory '../file.txt'

    Interactive Path Builder

    /
    home
    user
    documents
    data
    file.txt
    /

    Common OS Module Operations

    import os # Get current working directory current_dir = os.getcwd() # Check if file exists if os.path.exists('file.txt'): print('File exists') # Join path components path = os.path.join('folder', 'subfolder', 'file.txt') # Get file size size = os.path.getsize('file.txt') # List directory contents files = os.listdir('.')

    Working with CSV Files

    CSV Module Basics

    import csv # Writing CSV with open('data.csv', 'w', newline='') as file: writer = csv.writer(file) writer.writerow(['Name', 'Age', 'City']) writer.writerow(['Alice', '25', 'New York']) # Reading CSV with open('data.csv', 'r') as file: reader = csv.reader(file) for row in reader: print(row)

    Interactive CSV Demo

    Name Age City Occupation

    CSV DictWriter & DictReader

    import csv # Writing with DictWriter data = [ {'name': 'Alice', 'age': 25, 'city': 'NYC'}, {'name': 'Bob', 'age': 30, 'city': 'LA'} ] with open('data.csv', 'w', newline='') as file: fieldnames = ['name', 'age', 'city'] writer = csv.DictWriter(file, fieldnames=fieldnames) writer.writeheader() writer.writerows(data) # Reading with DictReader with open('data.csv', 'r') as file: reader = csv.DictReader(file) for row in reader: print(row['name'], row['age'])

    Working with JSON Files

    JSON Module Basics

    import json # Writing JSON data = { 'name': 'Alice', 'age': 25, 'skills': ['Python', 'JavaScript'] } with open('data.json', 'w') as file: json.dump(data, file, indent=4) # Reading JSON with open('data.json', 'r') as file: data = json.load(file) print(data['name'])

    Interactive JSON Demo

    Python Dictionary

    JSON Output

    JSON vs CSV Comparison

    Feature CSV JSON
    Structure Tabular (rows & columns) Hierarchical (nested objects)
    Data Types All strings (must convert) Multiple types (string, number, boolean, null)
    Best For Simple tabular data, spreadsheets Complex nested data, APIs
    Human Readable Very readable Readable with formatting
    File Size Smaller for simple data Larger due to formatting

    Exception Handling in File Operations

    Common File Exceptions

    FileNotFoundError

    Raised when trying to open a non-existent file in read mode.

    PermissionError

    Raised when lacking permission to access a file.

    IOError

    General input/output operation failure.

    IsADirectoryError

    Raised when trying to open a directory as a file.

    Try-Except-Finally Pattern

    try: # Try to open and read file with open('data.txt', 'r') as file: content = file.read() print(content) except FileNotFoundError: # Handle missing file print('Error: File not found!') except PermissionError: # Handle permission issues print('Error: No permission to read file!') except Exception as e: # Handle any other exceptions print(f'Unexpected error: {e}') finally: # Always executed (cleanup code) print('File operation completed')

    Interactive Exception Handler

    Test different exception scenarios:

    Best Practices

    1. Use Specific Exceptions: Catch specific exceptions before general ones.
    2. Use 'with' Statement: Ensures file is closed even if exception occurs.
    3. Provide Helpful Messages: Tell users what went wrong and how to fix it.
    4. Log Errors: In production, log errors for debugging.

    Complete Exception Handling Example

    import os def safe_file_read(filename): """Safely read a file with proper exception handling""" # Check if file exists first if not os.path.exists(filename): return None, "File does not exist" try: with open(filename, 'r', encoding='utf-8') as file: content = file.read() return content, None except PermissionError: return None, "Permission denied" except UnicodeDecodeError: return None, "File encoding error" except Exception as e: return None, f"Unexpected error: {str(e)}" # Usage content, error = safe_file_read('data.txt') if error: print(f"Error: {error}") else: print(content)

    File Handling Quiz

    Test your knowledge of Python file handling concepts

    Course Home