Your First Steps in Python: A Beginner to Intermediate Guide

Practical Examples and Use Cases

Section 11

File Handling: Reading from and Writing to Files

Your First Steps in Python: A Beginner to Intermediate GuideFile Handling: Reading from and Writing to Files

Now that we've covered the fundamentals of reading from and writing to files in Python, let's dive into some practical examples and common use cases. These scenarios will help solidify your understanding and showcase the real-world power of file handling.

Applications often store their settings and configurations in separate files. This allows for easy modification without altering the core code. We can read these files to load parameters like database credentials, API keys, or application-specific settings.

config.ini
[database]
host = localhost
port = 5432
username = admin
with open('config.ini', 'r') as f:
    for line in f:
        if '[' not in line and '=' in line:
            key, value = line.strip().split('=', 1)
            print(f"Setting: {key}, Value: {value}")

Logging is crucial for debugging and monitoring applications. We can write messages to a log file, capturing events, errors, or important information as they happen. This creates a historical record of the application's activity.

import datetime

def log_event(message):
    timestamp = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    with open('app.log', 'a') as f:
        f.write(f'{timestamp} - {message}\n')

log_event('Application started.')
# ... other application logic ...
log_event('User logged in.')
チャプターへ戻る