Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import os
- import csv
- import time
- from datetime import datetime
- # Folder to analyze
- TARGET_FOLDER = r"D:\Downloads"
- # CSV output file
- CSV_FILE = r"D:\Downloads\folder_metrics.csv"
- # Start timer
- start_time = time.perf_counter()
- file_count = 0
- folder_count = 0
- total_size_bytes = 0
- # Traverse directory
- for root, dirs, files in os.walk(TARGET_FOLDER):
- folder_count += len(dirs)
- file_count += len(files)
- for file in files:
- file_path = os.path.join(root, file)
- try:
- total_size_bytes += os.path.getsize(file_path)
- except (OSError, FileNotFoundError):
- pass
- # Convert bytes to MB
- total_size_mb = round(total_size_bytes / (1024 * 1024), 2)
- # End timer
- end_time = time.perf_counter()
- execution_time_sec = round(end_time - start_time, 3)
- # Current timestamp
- timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
- # Check if CSV exists
- file_exists = os.path.isfile(CSV_FILE)
- # Append data to CSV
- with open(CSV_FILE, mode="a", newline="", encoding="utf-8") as csvfile:
- writer = csv.writer(csvfile)
- if not file_exists:
- writer.writerow([
- "Timestamp",
- "File_Count",
- "Folder_Count",
- "Total_Size_MB",
- "Execution_Time_Sec"
- ])
- writer.writerow([
- timestamp,
- file_count,
- folder_count,
- total_size_mb,
- execution_time_sec
- ])
- # Print summary
- print(f"Timestamp : {timestamp}")
- print(f"Files : {file_count:,}")
- print(f"Folders : {folder_count:,}")
- print(f"Total Size (MB) : {total_size_mb:,.2f}")
- print(f"Execution Time (s) : {execution_time_sec}")
- print(f"Metrics appended to: {CSV_FILE}")
Advertisement
Add Comment
Please, Sign In to add comment