En este paso final, crearemos una aplicación más práctica que demuestre cómo usar la función print() con la redirección de archivos para generar un informe formateado. Este ejemplo mostrará cómo esta técnica se puede aplicar en escenarios del mundo real.
Creemos un script que genere un informe de ventas basado en algunos datos de muestra:
- Cree un nuevo archivo llamado
sales_report_generator.py en el directorio /home/labex/project
- Agregue el siguiente código al archivo:
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())
- Guarde el archivo y ejecútelo:
python3 sales_report_generator.py
Debería ver una salida que incluye:
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
Este ejemplo demuestra cómo crear un informe bien formateado utilizando la función print() con la redirección de archivos. El informe incluye encabezados, datos formateados en un diseño tabular e información de resumen.
Creando un sistema de rotación de registros dinámico
Creemos un ejemplo más que demuestre un sistema de rotación de registros, que crea un nuevo archivo de registro cada vez que se ejecuta el script:
- Cree un nuevo archivo llamado
rotating_log.py en el directorio /home/labex/project
- Agregue el siguiente código al archivo:
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())
- Guarde el archivo y ejecútelo:
python3 rotating_log.py
Debería ver una salida similar a:
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
Este ejemplo demuestra una aplicación más avanzada de la salida de archivos en Python. Cada vez que se ejecuta el script, crea un nuevo archivo de registro con una marca de tiempo en el nombre, lo que ayuda con la organización y gestión de registros.
Estos ejemplos prácticos muestran cómo redirigir la salida de la función print() a archivos se puede utilizar para crear aplicaciones útiles como generadores de informes y sistemas de registro. Las técnicas que ha aprendido en este laboratorio se pueden aplicar a muchos escenarios del mundo real donde necesita guardar la salida del programa para referencia o análisis posterior.