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 = adminwith 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.')Comma Separated Values (CSV) files are a very common format for storing tabular data. Python's built-in csv module makes it incredibly easy to read and write this data.