python

examples

examples.py🐍
"""
07 - File Handling: Examples
Run this file to see file operations in action!
"""

import os
import json
import csv
import tempfile
from pathlib import Path

print("=" * 60)
print("FILE HANDLING - EXAMPLES")
print("=" * 60)

# Create a temporary directory for our examples
temp_dir = tempfile.mkdtemp(prefix="python_learning_")
print(f"\nUsing temporary directory: {temp_dir}")

# =============================================================================
# 1. BASIC FILE OPERATIONS
# =============================================================================
print("\n--- 1. Basic File Operations ---\n")

# Writing to a file
file_path = os.path.join(temp_dir, "sample.txt")

# Using context manager (recommended!)
with open(file_path, 'w') as f:
    f.write("Hello, World!\n")
    f.write("This is line 2.\n")
    f.write("This is line 3.\n")

print(f"Created file: {file_path}")

# Reading entire file
with open(file_path, 'r') as f:
    content = f.read()
    print(f"File content:\n{content}")

# Reading line by line
print("Reading line by line:")
with open(file_path, 'r') as f:
    for line_num, line in enumerate(f, 1):
        print(f"  Line {line_num}: {line.strip()}")

# Reading all lines into a list
with open(file_path, 'r') as f:
    lines = f.readlines()
    print(f"\nAll lines as list: {lines}")

# Using splitlines() to avoid \n
with open(file_path, 'r') as f:
    lines = f.read().splitlines()
    print(f"Lines without \\n: {lines}")

# =============================================================================
# 2. FILE MODES
# =============================================================================
print("\n--- 2. File Modes ---\n")

# Append mode
with open(file_path, 'a') as f:
    f.write("This line was appended.\n")

with open(file_path, 'r') as f:
    print(f"After appending:\n{f.read()}")

# Write mode (truncates file)
new_file = os.path.join(temp_dir, "new_file.txt")
with open(new_file, 'w') as f:
    f.write("Fresh content!\n")
print(f"Created new file with 'w' mode")

# Read and write mode
with open(new_file, 'r+') as f:
    content = f.read()
    f.seek(0)  # Go back to beginning
    f.write("Modified: " + content)

with open(new_file, 'r') as f:
    print(f"After r+ modification: {f.read()}")

# =============================================================================
# 3. FILE POSITION AND SEEKING
# =============================================================================
print("\n--- 3. File Position and Seeking ---\n")

with open(file_path, 'r') as f:
    # Read first 10 characters
    chunk = f.read(10)
    print(f"First 10 chars: '{chunk}'")
    
    # Check position
    pos = f.tell()
    print(f"Current position: {pos}")
    
    # Seek to beginning
    f.seek(0)
    print(f"After seek(0), position: {f.tell()}")
    
    # Seek to end
    f.seek(0, 2)  # 0 offset from end (2)
    print(f"End of file position: {f.tell()}")

# =============================================================================
# 4. WRITING MULTIPLE LINES
# =============================================================================
print("\n--- 4. Writing Multiple Lines ---\n")

multi_file = os.path.join(temp_dir, "multi.txt")

# Using writelines()
lines = ["Line 1\n", "Line 2\n", "Line 3\n"]
with open(multi_file, 'w') as f:
    f.writelines(lines)

# Using print() with file parameter
with open(multi_file, 'a') as f:
    print("Line 4 via print()", file=f)
    print("Line 5 via print()", file=f)

with open(multi_file, 'r') as f:
    print(f"Multi-line file:\n{f.read()}")

# =============================================================================
# 5. PATHLIB (MODERN APPROACH)
# =============================================================================
print("\n--- 5. Pathlib (Modern Approach) ---\n")

# Create Path object
p = Path(temp_dir) / "pathlib_test.txt"

# Write text
p.write_text("Hello from pathlib!\nSecond line.")
print(f"Created: {p}")

# Read text
content = p.read_text()
print(f"Content: {content}")

# Path properties
print(f"\nPath properties:")
print(f"  Name: {p.name}")
print(f"  Stem: {p.stem}")
print(f"  Suffix: {p.suffix}")
print(f"  Parent: {p.parent}")
print(f"  Exists: {p.exists()}")
print(f"  Is file: {p.is_file()}")
print(f"  Is dir: {p.is_dir()}")

# List files in directory
print(f"\nFiles in temp directory:")
for item in Path(temp_dir).iterdir():
    print(f"  {item.name}")

# Glob patterns
print(f"\nAll .txt files:")
for txt_file in Path(temp_dir).glob("*.txt"):
    print(f"  {txt_file.name}")

# =============================================================================
# 6. JSON FILES
# =============================================================================
print("\n--- 6. JSON Files ---\n")

json_path = os.path.join(temp_dir, "data.json")

# Python data to JSON
data = {
    "name": "Alice",
    "age": 30,
    "hobbies": ["reading", "coding", "hiking"],
    "address": {
        "city": "New York",
        "country": "USA"
    }
}

# Write JSON
with open(json_path, 'w') as f:
    json.dump(data, f, indent=2)

print(f"Written JSON to {json_path}")

# Read JSON
with open(json_path, 'r') as f:
    loaded_data = json.load(f)

print(f"Loaded data: {loaded_data}")
print(f"Name: {loaded_data['name']}")
print(f"First hobby: {loaded_data['hobbies'][0]}")

# JSON string conversion
json_str = json.dumps(data, indent=2)
print(f"\nJSON as string:\n{json_str}")

# =============================================================================
# 7. CSV FILES
# =============================================================================
print("\n--- 7. CSV Files ---\n")

csv_path = os.path.join(temp_dir, "people.csv")

# Write CSV - list of lists
people_data = [
    ["Name", "Age", "City"],
    ["Alice", 30, "New York"],
    ["Bob", 25, "Los Angeles"],
    ["Charlie", 35, "Chicago"]
]

with open(csv_path, 'w', newline='') as f:
    writer = csv.writer(f)
    writer.writerows(people_data)

print(f"Written CSV to {csv_path}")

# Read CSV
print("\nReading CSV:")
with open(csv_path, 'r') as f:
    reader = csv.reader(f)
    for row in reader:
        print(f"  {row}")

# Write CSV with DictWriter
dict_csv_path = os.path.join(temp_dir, "people_dict.csv")
people_dicts = [
    {"name": "Alice", "age": 30, "city": "New York"},
    {"name": "Bob", "age": 25, "city": "Los Angeles"},
    {"name": "Charlie", "age": 35, "city": "Chicago"}
]

with open(dict_csv_path, 'w', newline='') as f:
    fieldnames = ["name", "age", "city"]
    writer = csv.DictWriter(f, fieldnames=fieldnames)
    writer.writeheader()
    writer.writerows(people_dicts)

# Read CSV with DictReader
print("\nReading CSV as dicts:")
with open(dict_csv_path, 'r') as f:
    reader = csv.DictReader(f)
    for row in reader:
        print(f"  {row['name']} is {row['age']} years old from {row['city']}")

# =============================================================================
# 8. BINARY FILES
# =============================================================================
print("\n--- 8. Binary Files ---\n")

binary_path = os.path.join(temp_dir, "binary.bin")

# Write binary data
binary_data = bytes([0, 1, 2, 3, 255, 254, 253])
with open(binary_path, 'wb') as f:
    f.write(binary_data)

print(f"Written binary data: {list(binary_data)}")

# Read binary data
with open(binary_path, 'rb') as f:
    read_data = f.read()

print(f"Read binary data: {list(read_data)}")

# Reading in chunks (for large files)
print("\nReading in chunks:")
with open(binary_path, 'rb') as f:
    chunk_size = 3
    while True:
        chunk = f.read(chunk_size)
        if not chunk:
            break
        print(f"  Chunk: {list(chunk)}")

# =============================================================================
# 9. FILE OPERATIONS (COPY, MOVE, DELETE)
# =============================================================================
print("\n--- 9. File Operations ---\n")

import shutil

# Copy file
source = file_path
dest = os.path.join(temp_dir, "copied.txt")
shutil.copy(source, dest)
print(f"Copied {os.path.basename(source)} to {os.path.basename(dest)}")

# Copy with metadata
shutil.copy2(source, os.path.join(temp_dir, "copied2.txt"))
print("Copied with metadata using copy2()")

# Move/rename file
old_name = os.path.join(temp_dir, "copied2.txt")
new_name = os.path.join(temp_dir, "renamed.txt")
shutil.move(old_name, new_name)
print(f"Renamed copied2.txt to renamed.txt")

# Get file size
file_size = os.path.getsize(file_path)
print(f"\nFile size of sample.txt: {file_size} bytes")

# Get file modification time
import time
mod_time = os.path.getmtime(file_path)
print(f"Last modified: {time.ctime(mod_time)}")

# =============================================================================
# 10. EXCEPTION HANDLING WITH FILES
# =============================================================================
print("\n--- 10. Exception Handling ---\n")

# Handle file not found
try:
    with open("nonexistent_file.txt", 'r') as f:
        content = f.read()
except FileNotFoundError:
    print("Caught FileNotFoundError - file doesn't exist")

# Handle permission error (example structure)
try:
    # This might fail on some systems
    with open("/root/protected.txt", 'w') as f:
        f.write("test")
except PermissionError:
    print("Caught PermissionError - no permission to write")
except Exception as e:
    print(f"Caught other error: {type(e).__name__}")

# Safe file reading pattern
def safe_read_file(filepath, default=""):
    """Safely read a file, return default if not found."""
    try:
        with open(filepath, 'r') as f:
            return f.read()
    except FileNotFoundError:
        return default
    except Exception as e:
        print(f"Error reading file: {e}")
        return default

result = safe_read_file("missing.txt", "File not found")
print(f"Safe read result: {result}")

# =============================================================================
# 11. TEMPORARY FILES
# =============================================================================
print("\n--- 11. Temporary Files ---\n")

# Create named temporary file
with tempfile.NamedTemporaryFile(mode='w', suffix='.txt', delete=False) as tf:
    tf.write("Temporary content")
    temp_path = tf.name
    print(f"Created temp file: {temp_path}")

# Read it back
with open(temp_path, 'r') as f:
    print(f"Temp file content: {f.read()}")

# Clean up
os.remove(temp_path)
print(f"Deleted temp file")

# Temporary directory
with tempfile.TemporaryDirectory() as tmpdir:
    print(f"\nCreated temp directory: {tmpdir}")
    # Directory is automatically deleted when block ends
print("Temp directory automatically deleted")

# =============================================================================
# 12. PRACTICAL EXAMPLES
# =============================================================================
print("\n--- 12. Practical Examples ---\n")

# Example 1: Count lines in a file
def count_lines(filepath):
    """Count non-empty lines in a file."""
    with open(filepath, 'r') as f:
        return sum(1 for line in f if line.strip())

line_count = count_lines(file_path)
print(f"Non-empty lines in sample.txt: {line_count}")

# Example 2: Find and replace in file
def find_replace(filepath, old_text, new_text):
    """Replace text in a file."""
    with open(filepath, 'r') as f:
        content = f.read()
    
    content = content.replace(old_text, new_text)
    
    with open(filepath, 'w') as f:
        f.write(content)

# Create a test file
test_file = os.path.join(temp_dir, "replace_test.txt")
with open(test_file, 'w') as f:
    f.write("Hello World! World is great.")

find_replace(test_file, "World", "Python")
with open(test_file, 'r') as f:
    print(f"After replacement: {f.read()}")

# Example 3: Log file appender
def log_message(log_file, message):
    """Append a timestamped message to log file."""
    from datetime import datetime
    timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    with open(log_file, 'a') as f:
        f.write(f"[{timestamp}] {message}\n")

log_path = os.path.join(temp_dir, "app.log")
log_message(log_path, "Application started")
log_message(log_path, "User logged in")
log_message(log_path, "Task completed")

print(f"Log file contents:")
with open(log_path, 'r') as f:
    print(f.read())

# =============================================================================
# CLEANUP
# =============================================================================
print("\n--- Cleanup ---\n")

# Clean up temporary directory
import shutil
shutil.rmtree(temp_dir)
print(f"Cleaned up temporary directory: {temp_dir}")

print("\n" + "=" * 60)
print("END OF EXAMPLES")
print("=" * 60)
Examples - Python Tutorial | DeepML