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.
data.csv
Name,Age,City
Alice,30,New York
Bob,25,Los Angelesimport csv
with open('data.csv', 'r') as f:
reader = csv.reader(f)
header = next(reader) # Skip header row
for row in reader:
name, age, city = row
print(f"Name: {name}, Age: {age}, City: {city}")You can use file writing to generate reports from your application's data. This could be anything from a simple text summary to a more structured report in a format like CSV or even HTML.
sales_data = [
{'product': 'Laptop', 'quantity': 5, 'price': 1200},
{'product': 'Keyboard', 'quantity': 10, 'price': 75}
]
with open('sales_report.txt', 'w') as f:
f.write('Sales Report\n')
f.write('--------------\n')
total_revenue = 0
for item in sales_data:
revenue = item['quantity'] * item['price']
f.write(f"Product: {item['product']}, Quantity: {item['quantity']}, Revenue: ${revenue}\n")
total_revenue += revenue
f.write(f'\nTotal Revenue: ${total_revenue}\n')For simpler applications or prototypes, you might store user-specific data directly in text files. This could be game scores, user preferences, or progress trackers.
user_score = 1500
with open('user_progress.txt', 'w') as f:
f.write(str(user_score))
with open('user_progress.txt', 'r') as f:
loaded_score = int(f.read())
print(f'Loaded score: {loaded_score}')Many external services or legacy systems might provide data in simple text formats. Being able to read and parse these files allows your Python programs to interact with a wider range of data sources.
graph TD
A[External Data Source] --> B{File Transfer}
B --> C[Python Script]
C -- Reads/Parses --> D[Application Logic]
These examples cover a range of common scenarios. As you become more comfortable with Python, you'll find even more innovative ways to leverage file handling in your projects.