AW Dev Rethought

🌟 The best way to predict the future is to invent it - Alan Kay

🧩 Python Automation Recipes – ⬇️ Automatic File Downloader


Description:

📌 Introduction

Downloading files one by one and renaming them manually gets repetitive fast — especially when working with reports, assets, datasets, or generated files.

This automation recipe shows how to download files from URLs and save them with organized naming using Python. It’s useful for report collection, asset syncing, content archiving, and many everyday automation workflows.


🔎 Explanation

  • The script reads a list of file URLs.
  • For each URL, it:
    • sends an HTTP request,
    • detects the file extension,
    • creates a timestamped or numbered filename,
    • saves the file into a target folder.
  • This gives you a predictable and organized download workflow instead of scattered filenames.

You can later extend this to:

  • read URLs from a CSV or text file,
  • group files into subfolders,
  • retry failed downloads,
  • log results.

✅ Key Takeaways

  • ⬇️ Download multiple files automatically from URLs.
  • 🗂️ Save them with clean, organized names.
  • ⚙️ Great for recurring data collection and file workflows.

Code Snippet:

from pathlib import Path
from datetime import datetime
import requests

# --- Step 1: Configuration ---

# Folder where downloaded files should be saved
DOWNLOAD_FOLDER = Path("")

# List of file URLs to download
URLS = [
    "https://example.com/file1.pdf",
    "https://example.com/file2.jpg",
    "https://example.com/file3.csv",
]

# Ensure download folder exists
DOWNLOAD_FOLDER.mkdir(exist_ok=True)

# --- Step 2: Download files ---
for index, url in enumerate(URLS, start=1):
    try:
        response = requests.get(url, timeout=15)
        response.raise_for_status()

        # Try to get file extension from URL
        extension = Path(url).suffix or ".bin"

        # Create organized filename with timestamp + index
        timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
        filename = f"download_{index}_{timestamp}{extension}"

        output_path = DOWNLOAD_FOLDER / filename

        # Save file content
        with output_path.open("wb") as f:
            f.write(response.content)

        print(f"File Downloaded: {filename}")

    except Exception as e:
        print(f"Failed to download from {url}")
        print(f"Error: {e}")

print("\nFile download process completed.")

Link copied!

Comments

Add Your Comment

Comment Added!