Creating a Practical Application - Report Generator
In this final step, we will create a more practical application that demonstrates how to use the print()
function with file redirection to generate a formatted report. This example will show how this technique can be applied in real-world scenarios.
Building a Sales Report Generator
Let's create a script that generates a sales report based on some sample data:
- Create a new file named
sales_report_generator.py
in the /home/labex/project
directory
- Add the following code to the file:
import datetime
## Sample sales data (product, quantity, price)
sales_data = [
{"product": "Laptop", "quantity": 5, "price": 899.99},
{"product": "Mouse", "quantity": 10, "price": 24.99},
{"product": "Keyboard", "quantity": 7, "price": 49.99},
{"product": "Monitor", "quantity": 3, "price": 149.99},
{"product": "Headphones", "quantity": 12, "price": 79.99}
]
def generate_sales_report(filename):
"""Generate a formatted sales report and save it to a file."""
today = datetime.datetime.now().strftime("%Y-%m-%d")
with open(filename, "w") as report_file:
## Print the report header
print("=" * 60, file=report_file)
print(f"SALES REPORT - Generated on {today}", file=report_file)
print("=" * 60, file=report_file)
print("", file=report_file)
## Print the table header
print(f"{'Product':<15} {'Quantity':<10} {'Price ($)':<10} {'Total ($)':<10}", file=report_file)
print("-" * 50, file=report_file)
## Print sales data and calculate totals
grand_total = 0
total_items = 0
for item in sales_data:
product = item["product"]
quantity = item["quantity"]
price = item["price"]
total = quantity * price
print(f"{product:<15} {quantity:<10} {price:<10.2f} {total:<10.2f}", file=report_file)
grand_total += total
total_items += quantity
## Print the summary
print("-" * 50, file=report_file)
print(f"{'Total':<15} {total_items:<10} {'':<10} {grand_total:<10.2f}", file=report_file)
print("", file=report_file)
print("=" * 60, file=report_file)
print("End of Report", file=report_file)
## Generate the report
report_filename = "sales_report.txt"
generate_sales_report(report_filename)
print(f"Sales report has been generated: {report_filename}")
print("\nContents of the sales report:")
with open(report_filename, "r") as file:
print(file.read())
- Save the file and run it:
python3 sales_report_generator.py
You should see output that includes:
Sales report has been generated: sales_report.txt
Contents of the sales report:
============================================================
SALES REPORT - Generated on 2023-09-10
============================================================
Product Quantity Price ($) Total ($)
--------------------------------------------------
Laptop 5 899.99 4499.95
Mouse 10 24.99 249.90
Keyboard 7 49.99 349.93
Monitor 3 149.99 449.97
Headphones 12 79.99 959.88
--------------------------------------------------
Total 37 6509.63
============================================================
End of Report
This example demonstrates how to create a nicely formatted report using the print()
function with file redirection. The report includes headers, formatted data in a tabular layout, and summary information.
Creating a Dynamic Log Rotation System
Let's create one more example that demonstrates a log rotation system, which creates a new log file each time the script runs:
- Create a new file named
rotating_log.py
in the /home/labex/project
directory
- Add the following code to the file:
import datetime
import os
def create_log_file():
"""Create a new log file with a timestamp in the filename."""
timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
log_dir = "logs"
## Create logs directory if it doesn't exist
if not os.path.exists(log_dir):
os.makedirs(log_dir)
return os.path.join(log_dir, f"log_{timestamp}.txt")
def log_event(log_file, event_type, message):
"""Log an event to the specified log file."""
timestamp = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
with open(log_file, "a") as f:
print(f"[{timestamp}] [{event_type.upper()}] {message}", file=f)
## Create a new log file
log_filename = create_log_file()
print(f"Created new log file: {log_filename}")
## Simulate some application events
log_event(log_filename, "info", "Application started")
log_event(log_filename, "info", "Initializing modules...")
log_event(log_filename, "warning", "Configuration file not found, using defaults")
log_event(log_filename, "info", "Processing data batch #1")
log_event(log_filename, "error", "Failed to connect to database server")
log_event(log_filename, "info", "Retrying connection in 5 seconds")
log_event(log_filename, "info", "Connection established")
log_event(log_filename, "info", "Application shutting down")
print("\nLog file contents:")
with open(log_filename, "r") as f:
print(f.read())
- Save the file and run it:
python3 rotating_log.py
You should see output similar to:
Created new log file: logs/log_20230910_153045.txt
Log file contents:
[2023-09-10 15:30:45] [INFO] Application started
[2023-09-10 15:30:45] [INFO] Initializing modules...
[2023-09-10 15:30:45] [WARNING] Configuration file not found, using defaults
[2023-09-10 15:30:45] [INFO] Processing data batch #1
[2023-09-10 15:30:45] [ERROR] Failed to connect to database server
[2023-09-10 15:30:45] [INFO] Retrying connection in 5 seconds
[2023-09-10 15:30:45] [INFO] Connection established
[2023-09-10 15:30:45] [INFO] Application shutting down
This example demonstrates a more advanced application of file output in Python. Each time the script runs, it creates a new log file with a timestamp in the name, which helps with log organization and management.
These practical examples show how redirecting the print()
function's output to files can be used to create useful applications like report generators and logging systems. The techniques you've learned in this lab can be applied to many real-world scenarios where you need to save program output for later reference or analysis.