実用的なアプリケーションの作成 - レポートジェネレーター
この最終ステップでは、print() 関数をファイルリダイレクトと組み合わせて、フォーマットされたレポートを生成する方法を示す、より実用的なアプリケーションを作成します。この例では、この手法を実際のシナリオに適用する方法を示します。
売上レポートジェネレーターの構築
いくつかのサンプルデータに基づいて売上レポートを生成するスクリプトを作成しましょう。
/home/labex/project ディレクトリに sales_report_generator.py という名前の新しいファイルを作成します。
- ファイルに次のコードを追加します。
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())
- ファイルを保存して実行します。
python3 sales_report_generator.py
次のような出力が表示されるはずです。
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
この例では、ファイルリダイレクトを使用して print() 関数で、適切にフォーマットされたレポートを作成する方法を示しています。レポートには、ヘッダー、表形式のレイアウトでフォーマットされたデータ、および要約情報が含まれています。
動的ログローテーションシステムの作成
スクリプトが実行されるたびに新しいログファイルを作成するログローテーションシステムを示す、もう 1 つの例を作成しましょう。
/home/labex/project ディレクトリに rotating_log.py という名前の新しいファイルを作成します。
- ファイルに次のコードを追加します。
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())
- ファイルを保存して実行します。
python3 rotating_log.py
次のような出力が表示されるはずです。
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
この例は、Python でのファイル出力のより高度なアプリケーションを示しています。スクリプトが実行されるたびに、名前のタイムスタンプが付いた新しいログファイルが作成され、ログの整理と管理に役立ちます。
これらの実用的な例は、print() 関数の出力をファイルにリダイレクトして、レポートジェネレーターやロギングシステムなどの便利なアプリケーションを作成する方法を示しています。この実験で学習したテクニックは、後で参照または分析するためにプログラム出力を保存する必要がある多くの実際のシナリオに適用できます。