Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Python can take repetitive chores off your hands: sorting downloads, renaming a batch of files, collecting items for review, cleaning a CSV, or producing a recurring summary. The first four examples below use Python’s standard library for local files; the final example shows the difference between writing a report and keeping it running on a schedule.

Each script is a starting point you can adapt. Begin with a small test folder or a copy of your data, and read the preview before allowing a script to change files. Python documents the file and path operations used here in its file and directory documentation.

Before running scripts that change files

  • Make a test folder with copies of the files you intend to process.
  • Start with a specific folder, not your entire home directory or drive.
  • Print the proposed changes first, then require an explicit apply option.
  • Keep the original CSV and write transformed data to a new file.
  • Check the result before deleting or overwriting anything.

These are practical safeguards for scripts that can move or rename files; they are not a special Python requirement.

1. Sort a folder by file type

This script groups files into subfolders named for their extensions—for example, .pdf files go into pdf. It skips folders and files without an extension. By default it only prints a proposed move list; pass --apply to perform the moves.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
Elebase USB to USB C Adapter for iPhone 18 Pro Max,USBC Car Charger Adapter
  • Read Before You Buy — No Video Output: These adapters support charging and USB 2.0 data transfer, but cannot transmit video signals. Except for standard USB webcams (which use USB data only), they are not compatible with HDMI/DisplayPort cables, video-capable USB-C hubs, or docking stations with video output.
  • Convert USB-A Ports to USB-C: Designed to connect USB-C earphones, cables, flash drives, card readers, and other USB-C accessories to standard USB-A ports. Plug-and-play with no drivers or software required.
  • Aluminum Alloy Housing: Built with a sturdy aluminum alloy shell that aids in heat dissipation and protects against daily wear and scratches. Designed to maintain a stable and secure connection.
  • Compact & Travel-Friendly: The ultra-compact design allows the adapter to stay plugged into your device without blocking adjacent ports or adding bulk, reducing wear and tear on your original USB ports.
  • 12-Month Warranty: Backed by a 12-month manufacturer warranty for peace of mind. Designed to meet strict quality control standards for reliable everyday performance.
from pathlib import Path
import argparse
import shutil

parser = argparse.ArgumentParser()
parser.add_argument("folder", type=Path, help="Folder whose files should be sorted")
parser.add_argument("--apply", action="store_true", help="Perform the proposed moves")
args = parser.parse_args()

root = args.folder.expanduser().resolve()
if not root.is_dir():
    raise SystemExit(f"Not a folder: {root}")

moves = []
for item in root.iterdir():
    if not item.is_file() or not item.suffix:
        continue
    destination = root / item.suffix[1:].lower() / item.name
    if destination.exists():
        print(f"SKIP (destination exists): {item.name} -> {destination}")
        continue
    moves.append((item, destination))

for source, destination in moves:
    print(f"{source.name} -> {destination.parent.name}/{destination.name}")

if args.apply:
    for source, destination in moves:
        destination.parent.mkdir(exist_ok=True)
        shutil.move(str(source), str(destination))
else:
    print("Preview only. Run again with --apply to move these files.")

Save it as sort_files.py. Run python sort_files.py "path/to/test-folder" to preview, then add --apply only when the list looks right. The script deliberately skips a move if a file with that name already exists in the target folder.

2. Batch-rename files with a preview

Batch renaming is useful when filenames need a consistent prefix or pattern. This example adds invoice_ to every PDF in a chosen folder. It builds and prints the full mapping first, skips conflicts, and changes names only when run with --apply.

from pathlib import Path
import argparse

parser = argparse.ArgumentParser()
parser.add_argument("folder", type=Path)
parser.add_argument("--apply", action="store_true")
args = parser.parse_args()

root = args.folder.expanduser().resolve()
if not root.is_dir():
    raise SystemExit(f"Not a folder: {root}")

renames = []
for old_path in sorted(root.iterdir()):
    if not old_path.is_file() or old_path.suffix.lower() != ".pdf":
        continue
    new_path = old_path.with_name("invoice_" + old_path.name)
    if new_path.exists():
        print(f"SKIP (destination exists): {old_path.name} -> {new_path.name}")
        continue
    renames.append((old_path, new_path))

for old_path, new_path in renames:
    print(f"{old_path.name} -> {new_path.name}")

if args.apply:
    for old_path, new_path in renames:
        old_path.rename(new_path)
else:
    print("Preview only. Run again with --apply to rename these files.")

Run it as python rename_pdfs.py "path/to/test-folder", inspect the old-name/new-name pairs, then add --apply to commit them. To use another rule, change the expression that constructs new_path; inspect the resulting mapping before applying it.

Rank #2
Anker USB-C Hub, 5-in-1 USB Hub for Laptops, 4K HDMI Multiport Adapter
  • 5-in-1 USB-C Hub: Experience comprehensive connectivity featuring a Power Delivery input, two USB-A 2.0 ports, a USB-A 3.0 port, and an HDMI port. (Note: The USB-C power delivery input port is only for connecting an external wall charger to power your laptop and cannot power peripheral devices.)
  • 90W Pass-Through Charging: Achieve optimal charging with 90W pass-through power to your laptop, supported by a total input of 100W, with the hub reserving 10W for operational efficiency. (Note: Wall charger not included.)
  • Quick Data Transfers: Accelerate your productivity with rapid data transfers using a high-speed 5Gbps USB 3.0 port and two 480Mbps USB 2.0 ports.
  • 4K HDMI Display: Enhance your visual experience with a hub capable of delivering 4K resolution at 30Hz in both mirror and extend modes. Please note that this hub is compatible with MacBook (macOS 12 and newer), Windows 10 and 11, ChromeOS, and laptops equipped with DP Alt Mode and Power Delivery. Note: This device is not compatible with Linux.
  • What You Get: Anker USB-C Hub (5-in-1, 4K HDMI), welcome guide, 18-month warranty, and our friendly customer service.

3. Find and copy matching files into a review folder

Use a wildcard pattern when you want to gather likely matches without moving or deleting the originals. This example copies all .pdf files in one folder into a separate review folder. The destination must not be inside the source folder, and existing destination files are left untouched.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
from pathlib import Path
import argparse
import shutil

parser = argparse.ArgumentParser()
parser.add_argument("source", type=Path)
parser.add_argument("destination", type=Path)
parser.add_argument("--apply", action="store_true")
args = parser.parse_args()

source = args.source.expanduser().resolve()
destination = args.destination.expanduser().resolve()
if not source.is_dir():
    raise SystemExit(f"Not a source folder: {source}")
if destination == source or source in destination.parents:
    raise SystemExit("Choose a destination outside the source folder")

matches = sorted(path for path in source.glob("*.pdf") if path.is_file())
for path in matches:
    target = destination / path.name
    if target.exists():
        print(f"SKIP (destination exists): {path.name}")
    else:
        print(f"{path.name} -> {target}")

if args.apply:
    destination.mkdir(parents=True, exist_ok=True)
    for path in matches:
        target = destination / path.name
        if not target.exists():
            shutil.copy2(path, target)
else:
    print("Preview only. Run again with --apply to copy matching files.")

Run python collect_pdfs.py "path/to/source" "path/to/review" first. Add --apply after checking the matches. Change "*.pdf" to another pattern, such as "*.txt", to adjust the selection. For a nested search, Path.rglob can search subfolders, but then review the list carefully: files in different subfolders can share the same filename.

Python’s tutorial covers wildcard file lists with glob and higher-level file management with shutil.

Rank #3
Sale
Anker USB C Hub, 7in1 Multi-Port USB Adapter, 4K@60Hz USBC to HDMI Splitter
  • Sleek 7-in-1 USB-C Hub: Features an HDMI port, two USB-A 3.0 ports, and a USB-C data port, each providing 5Gbps transfer speeds. It also includes a USB-C PD input port for charging up to 100W and dual SD and TF card slots, all in a compact design.
  • Flawless 4K@60Hz Video with HDMI: Delivers exceptional clarity and smoothness with its 4K@60Hz HDMI port, making it ideal for high-definition presentations and entertainment. (Note: Only the HDMI port supports video projection; the USB-C port is for data transfer only.)
  • Double Up on Efficiency: The two USB-A 3.0 ports and a USB-C port support a fast 5Gbps data rate, significantly boosting your transfer speeds and improving productivity.
  • Fast and Reliable 85W Charging: Offers high-capacity, speedy charging for laptops up to 85W, so you spend less time tethered to an outlet and more time being productive.
  • What You Get: Anker USB-C Hub (7-in-1), welcome guide, 18-month warranty, and our friendly customer service.

4. Clean and summarize a CSV

The standard-library csv module is enough for many plain CSV tasks. This example trims whitespace in every cell, keeps rows whose Status field is Paid, totals their Amount values, and writes the cleaned rows to a separate file. It expects a header row with columns named exactly Status and Amount, and amounts that can be parsed as numbers.

import argparse
import csv
from decimal import Decimal, InvalidOperation
from pathlib import Path

parser = argparse.ArgumentParser()
parser.add_argument("input", type=Path)
parser.add_argument("output", type=Path)
args = parser.parse_args()

input_path = args.input.expanduser().resolve()
output_path = args.output.expanduser().resolve()
if input_path == output_path:
    raise SystemExit("Choose a different output path to preserve the original")

try:
    with input_path.open("r", newline="", encoding="utf-8-sig") as source:
        reader = csv.DictReader(source)
        if not reader.fieldnames or not {"Status", "Amount"}.issubset(reader.fieldnames):
            raise SystemExit("CSV must have Status and Amount headers")

        rows = []
        total = Decimal("0")
        for row in reader:
            cleaned = {key: (value or "").strip() for key, value in row.items()}
            if cleaned["Status"].casefold() != "paid":
                continue
            try:
                total += Decimal(cleaned["Amount"])
            except InvalidOperation:
                raise SystemExit(f"Invalid Amount value: {cleaned['Amount']!r}")
            rows.append(cleaned)
except OSError as error:
    raise SystemExit(f"Could not read input: {error}")

with output_path.open("w", newline="", encoding="utf-8") as target:
    writer = csv.DictWriter(target, fieldnames=reader.fieldnames)
    writer.writeheader()
    writer.writerows(rows)

print(f"Paid rows: {len(rows)}")
print(f"Paid total: {total}")
print(f"Cleaned rows written to: {output_path}")

Run python clean_csv.py "transactions.csv" "paid_cleaned.csv". Review the new file and printed total against a small sample you understand. This is a simple exact-match filter, not a general spreadsheet formula engine. Python’s tutorial notes that CSV is commonly used for exchange with databases and spreadsheets: standard-library tutorial.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

5. Generate a recurring report or reminder

Separate report generation from scheduling: first make a script that can produce one report on demand, then decide how it should run repeatedly. For example, adapt the CSV script above so it writes a dated summary file each time it runs. If the task should run while your script stays open, the third-party schedule package offers a readable in-process API:

Rank #4
Sale
UGREEN USB to USB C Adapter Combo 4-Pack, 10Gbps USB C Converter Space Gray
  • Dual Converters, Infinite Potential:Includes 2× USB C male to USB A female adapters and 2× USB A male to USB C female adapters. Perfect for a wide range of uses—tablets with Bluetooth keyboards, expand USB ports on macbook, and more. Two different converters for all your daily needs
  • Next-Level 10Gbps & 3A Charging: No more slow 480Mbps, this usb to usb c adapter has a transfer speed of up to 10Gbps, allowing you to do more transferring in less time. This usb adapter fits both USB A and USB C charger, supporting up to 3A fast charging
  • Upgraded Exquisite Craftsmanship: With an aluminum alloy housing and metal connector, the usbc to usb adapter is extremely durable and sturdy. Rigorously tested to withstand more than 10,000 times of plugging and unplugging, ensuring long-lasting performance
  • Broad Compatible: The usb c to usb adapter widely supports all USB C/ USB A devices like laptops, tablets, cellphones, car chargers, and phone chargers. Such as compatible with MacBook Pro/Air 2023/2022, Thunderbolt 4/3 Devices,Apple MagSafe Watch 9/8/7/SE/Ultra, iPad Pro 2022/2021, Samsung Galaxy S23/S20/S10, and iPhone 17/16/15 Pro. Plug and play
  • Please Note: To reach 10Gbps speed, keep the cable under 3.3 ft. For USB A Male to USB C adapters, try flipping the USB C connector. USB C Male to USB A adapters support bidirectional 10Gbps transfer within 3.3 ft
import schedule
import time
from datetime import datetime
from pathlib import Path


def make_report():
    # Replace this with a summary of your permitted local input.
    report = f"Report generated: {datetime.now().isoformat(timespec='minutes')}n"
    output = Path("reports")
    output.mkdir(exist_ok=True)
    filename = output / f"report-{datetime.now():%Y-%m-%d_%H-%M}.txt"
    filename.write_text(report, encoding="utf-8")
    print(f"Wrote {filename}")


schedule.every().day.at("09:00").do(make_report)

while True:
    schedule.run_pending()
    time.sleep(30)

Install the dependency with python -m pip install schedule, save the script, and run it with Python. The process must remain running for the job to fire; the example uses the machine’s local time. Stop it with Ctrl+C. The package’s own stable documentation says it is not intended as a one-size-fits-all scheduler.

When the script needs to run unattended

For a job that should run even when you are not watching an open terminal, use the task scheduler provided by your operating system and configure it to launch the Python interpreter with the script. The exact setup differs by operating system and installation, so test the scheduled task manually first and check where its output and errors go. A scheduler can start a script; it does not remove the need to handle missing input files, permissions, network availability, or failures inside the script.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Which tasks can stay local?

Sorting, renaming, copying, and reading or writing a CSV can be local operations using Python’s standard library. Python’s Standard Library includes tools such as pathlib, shutil, and csv, and also provides facilities for working with email and other common tasks. The examples here do not send files anywhere.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Best Value
Anker USB C Hub, 5-in-1 USBC to HDMI Splitter with 4K Display
  • 5-in-1 Connectivity: Equipped with a 4K HDMI port, a 5 Gbps USB-C data port, two 5 Gbps USB-A ports, and a USB C 100W PD-IN port. Note: The USB C 100W PD-IN port supports only charging and does not support data transfer devices such as headphones or speakers.
  • Powerful Pass-Through Charging: Supports up to 85W pass-through charging so you can power up your laptop while you use the hub. Note: Pass-through charging requires a charger (not included). Note: To achieve full power for iPad, we recommend using a 45W wall charger.
  • Transfer Files in Seconds: Move files to and from your laptop at speeds of up to 5 Gbps via the USB-C and USB-A data ports. Note: The USB C 5Gbps Data port does not support video output.
  • HD Display: Connect to the HDMI port to stream or mirror content to an external monitor in resolutions of up to 4K@30Hz. Note: The USB-C ports do not support video output.
  • What You Get: Anker 332 USB-C Hub (5-in-1), welcome guide, our worry-free 18-month warranty, and friendly customer service.

Other formats or services may need more setup: Excel workbooks, PDFs, web pages, and service APIs can require an additional package, credentials, or service-specific configuration. Avoid sending confidential data to an external service unless its handling is appropriate for that data. Reusable command-line options can also be built with Python’s argparse module, as used in the file examples above.

Keep learning at your own pace

If you want a guided path beyond these small scripts, Al Sweigart’s Automate the Boring Stuff with Python is available to read online from the author’s official site. It is an optional learning resource, not a prerequisite for adapting the examples.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.