Sorting files, rebuilding reports or preparing the same messages? These ten Python automation examples help you recognise a suitable task, define a small first version and check the result.
Python can automate repetitive tasks such as sorting files, combining exports, preparing reports and assembling documents. The best opportunities have clear rules, repeat often and produce results you can check. Time savings depend on setup, review and maintenance as well as the manual work replaced.
Think about the last task you completed almost exactly as you did the week before. Did you rename another folder of downloads, rebuild a spreadsheet summary or prepare the same report message?
That familiar routine could be a useful starting point. These ten Python automation examples show what to build, what you need to know and how to check the result. The first includes a complete starter script.
Which task matches the work you repeat?
Start with the manual step you recognise. You do not need to build every example—or install every library—to benefit from one useful automation.
|
Repeated manual work |
Python automation task |
Starting knowledge |
|
Sorting incoming documents |
Organise files into folders |
Loops, conditions and paths |
|
Applying naming conventions |
Rename a batch of files |
Strings and paths |
|
Packaging project materials |
Create dated archives |
File handling |
|
Copying recurring exports |
Combine CSV files |
Tables and validation |
|
Rebuilding spreadsheet summaries |
Refresh an Excel report |
DataFrames and grouping |
|
Assembling document packs |
Merge PDFs |
Lists and paths |
|
Preparing image sizes |
Resize images in batches |
Loops and dimensions |
|
Investigating repeated files |
Report duplicate candidates |
File reading and comparison |
|
Preparing similar messages |
Create email drafts |
Templates and structured fields |
|
Retrieving service data |
Download an API export |
HTTP, JSON and error handling |
Local-file tasks are usually easier to isolate for practice. External services add requirements such as access settings, network handling and response checks.

What you need before you start
To run and adapt these examples, you should recognise variables, loops, conditions and functions, and know how to run a Python file.
You should also be able to identify the input folder, explain the processing rule and describe the expected output. If you cannot state the rule yet, clarify the task before writing code.
Some tools, including pathlib, csv and zipfile, come with Python. Others, such as pandas, Pillow and pypdf, require installation in your chosen environment.
The starter script below uses only Python’s standard library. Its package contains fictional sample files and reference output. Only this starter script was executed and checked for this article; the remaining sections describe practical tasks you can develop next.
1. Sort incoming files into the right folders
If you repeatedly separate documents, images and data exports, start with a simple extension-based rule. For example, .txt files go into Documents, .csv files into Data and unrecognised extensions into Other.
The starter script uses pathlib for paths and shutil to copy file contents. It previews the destinations first, then creates organised copies when you add --apply. It does not move or delete the originals.
Its scope is deliberately small: ordinary files directly inside one folder. Subfolders and symbolic links are skipped. A symbolic link is a filesystem reference to another location.
Output: Categorised copies and a manifest.csv listing each source filename and output path.
Check: Compare file counts and contents, and confirm the originals remain unchanged.
Try the starter script
[Download placement: Python automation starter package]
Extract the supplied package. Keep organise_files.py beside practice_inbox. The expected folder contains reference output; the script does not read it.
Save the following as organise_files.py if you are using your own practice files:
import argparse import csv import shutil from pathlib import PathBASE = Path(__file__).resolve().parentGROUPS = { '.txt': 'Documents', '.md': 'Documents', '.pdf': 'Documents', '.docx': 'Documents', '.csv': 'Data', '.xlsx': 'Data', '.json': 'Data', '.jpg': 'Images', '.jpeg': 'Images', '.png': 'Images',}def organise(source, destination, apply=False): if source.is_symlink() or not source.is_dir(): raise ValueError('Input must be an existing ordinary folder.') if destination.exists() or destination.is_symlink(): raise FileExistsError('Output exists. Archive or remove it before rerunning.') source = source.resolve() destination = destination.resolve() if source == destination or source in destination.parents: raise ValueError('Output must be outside the input folder.') plan, skipped = [], 0 for item in sorted(source.iterdir(), key=lambda path: path.name): if item.is_symlink() or not item.is_file(): skipped += 1 continue category = GROUPS.get(item.suffix.lower(), 'Other') relative_target = Path(category) / item.name plan.append((item, relative_target)) print(f'{item.name} -> {relative_target.as_posix()}') if not plan: raise ValueError('No ordinary files found. Nothing was copied.') if not apply:
Preview the proposed copies:
python organise_files.py
For the supplied sample, the final preview lines are:
Preview: 6 files | Skipped: 1
No files changed. Run again with --apply to create copies.
After inspecting the plan, create the copies:
python organise_files.py --apply
Expected completion message:
Copied: 6 | Skipped: 1
Original files were left in place. See organised/manifest.csv.
The output contains six copied files plus the manifest. The skipped item is a subfolder. Unknown extensions go into Other.
If your computer uses python3 or py, use that command consistently. This script was tested with Python 3.12.14 on Linux; other environments were not part of that execution test.
An existing organised folder stops the run. Inspect and archive or remove that generated folder before rerunning. If a copy fails, partial output may remain; inspect it before retrying. Run one instance at a time and keep the inputs unchanged during copying.
The Python pathlib documentation explains the path operations used here. Python 3.15.0 documentation
2. Rename batches of files consistently
Perhaps the files are already in the right folder, but their names are inconsistent. A renaming script can apply an agreed pattern such as a project code, date and sequence number.
Start by producing a before-and-after preview using pathlib and string formatting. Preserve each extension and keep an old-to-new mapping.
Output: Consistent filenames and a mapping log.
Check: Every proposed destination must be unique. Decide what happens if it already exists and what a second run should do. A log helps investigation, but does not itself implement an undo function.
This matters across operating systems: Python documents that Path.rename() can replace an existing file silently on Unix. Define collision handling rather than assuming the operation will refuse an overwrite.
3. Create a dated archive of project files
If you regularly package the same project materials, Python can collect an agreed set into a dated ZIP file.
Use zipfile with an explicit input list and keep the destination outside the source folder. Include a manifest so you can see what was selected.
Output: A dated archive and its file list.
Check: Compare the archive members with the manifest, check archive integrity and extract representative files. A successful archive check does not prove that you selected the correct documents.
Begin without automatic deletion of older archives. Packaging files is useful on its own; storage retention and a complete backup strategy need separate decisions.
The Python zipfile documentation describes archive creation and integrity checks. Python 3.15.0 documentation
4. Combine recurring CSV exports
Copying weekly exports into one table is a natural candidate when their structure is consistent.
Use Python’s csv module for straightforward fixed-column processing, or pandas when you need its table operations. Define the delimiter, encoding and required headers before combining records.
Output: A consolidated CSV file and a visible record of exceptions.
Check: Confirm unique headers, preserve text identifiers and reconcile accepted and rejected record counts. Decide whether repeated identifiers represent duplicates or legitimate multiple entries.
For example, 00125 may be an identifier whose leading zeros matter. Treating it as a number changes its representation. Do not silently remove incomplete rows just to produce a tidy-looking output.
Reference: Python CSV reading and writing.
5. Refresh an Excel summary report
When the same workbooks arrive every reporting period, a script can read the agreed sheets, validate records and create a new summary.
pandas is useful for table processing and aggregation. openpyxl supports workbook and cell operations, including formatting within its capabilities.
Output: A new report containing a summary, accepted records and records needing review.
Check: Compare the report with a small sample whose counts and totals you already know. Explain which records are excluded from the figures.
Reading tables and exporting them again does not preserve every feature of the source workbook. For a complete example and its limitations, continue with How to Automate Excel with Python: A Practical Guide.
6. Merge PDFs in a defined order
Assembling a recurring document pack can mean opening several PDFs, checking their sequence and saving a combined version.
A small pypdf script can assemble an explicit ordered list into a new document. Start with known sample documents rather than an unrestricted folder of files.
Output: One combined PDF.
Check: Verify the total page count, the first page of each section and representative page appearance. Correct page count alone does not establish correct order.
Keep the first version focused on assembly. Extracting text from scanned invoices or handling specialised document features introduces different requirements.
The pypdf merging documentation explains its document-assembly operations. pypdf 6.21.1 documentation
7. Resize images for repeated publishing tasks
Preparing dozens of images for a website or catalogue can involve repeating the same size adjustment.
Pillow can create resized copies within a chosen size boundary. Specify supported formats and whether you want to preserve the whole image or crop it to a fixed shape.
Output: A separate folder of prepared images.
Check: Inspect dimensions, aspect ratio, orientation and representative outputs. Include both portrait and landscape samples. Account for orientation information stored in photographs.
Keep the originals. Changing dimensions does not guarantee a particular file size or acceptable appearance, so those requirements need their own checks.
The Pillow ImageOps documentation covers orientation and different sizing operations. Pillow (PIL Fork) 13.0.0 documentation
8. Find duplicate files for review
Similar filenames can make a folder look duplicated even when its contents differ. Conversely, identical files can have completely different names.
Use file size and a content digest, such as SHA-256 through hashlib, to group candidates. Confirm matching contents before deciding what should happen to them.
Output: A review report with candidate groups and file locations.
Check: Test identical bytes saved under different names, and different content saved in files of the same size. Neither names nor sizes alone establish duplication.
Keep deletion outside the first version. Even identical content may exist in two locations for a reason. The report should help you investigate, rather than make that decision for you.
9. Prepare recurring email drafts
If you repeatedly prepare a report message with the same structure, automate its preparation before considering automatic sending.
Python’s email.message can build messages from defined fields and save them as local files. Use fictional recipients while developing the template.
Output: Reviewable message files with the expected subject, body and attachments.
Check: Verify recipients, missing placeholders, dates and attachments. A correctly generated message can still contain the wrong report or an outdated figure.
Local files do not automatically appear in Outlook or Gmail’s Drafts folder. Connecting to a particular mailbox is a separate integration task.
The Python email examples distinguish message construction, storage and sending.
10. Download a repeatable API data export
An API gives programs a structured way to request data. If a service provides one, you may be able to replace repeated manual retrieval with a defined request and local export.
Use Requests or the provider’s documented client. Define the fields, period and completeness checks before treating the response as usable data.
Output: A timestamped data file with retrieval information.
Check: Confirm the response status, expected structure, required fields, missing values and whether results span multiple pages. Successful JSON decoding does not itself establish a successful request.
Start with a saved sample response. Then add the live request, explicit timeouts and expected error handling.
Reference: Requests quickstart documentation. Requests 2.34.2 documentation
Which task should you automate first?
Choose something frequent, bounded and easy to inspect. A folder preview or a small CSV combination is usually a clearer starting point than a process involving several accounts and services.
Write your rule in one sentence: “Copy these files into folders based on their extensions” is clearer than “organise my computer”.
Next, predict the result for a small sample. Then run the script and compare the output with your prediction.
Where you struggle tells you what to practise. If you cannot define the rule, clarify the process. If you can explain it but cannot express it in code, focus on conditions and functions. If you cannot tell whether the result is right, improve the example and its checks before adding more automation.
Will automation actually save you time?
Consider the repeated manual effort alongside setup, review and maintenance. Track unattended processing time separately from the time you actively spend on the task.
Here is a hypothetical example, not a measured result:
|
Item |
Time |
|
Manual work: 20 runs × 15 minutes |
300 minutes |
|
Automated active/review effort: 20 runs × 3 minutes |
−60 minutes |
|
Initial setup |
−90 minutes |
|
Maintenance |
−15 minutes |
|
Net saving for the period |
135 minutes |
The same script used once might not repay the setup effort. Used repeatedly with stable inputs, it may become worthwhile. Measure your own routine rather than borrowing someone else’s time-saving claim.
Check the result before scheduling the task
Before unattended execution, confirm that the script selects the right inputs, produces traceable outputs and makes skipped or rejected items visible.
Run it twice during testing. The second run should follow a documented policy: refuse existing output, create a new version or avoid repeating completed work. Decide how partial failures will be noticed and investigated.
Keep task-specific checks close to their examples. A PDF needs an order check; a CSV needs record checks; a message needs recipient and attachment checks.
Scheduling starts a task at a chosen time. It does not prove the result is correct. Running a script manually can still automate all the repetitive steps inside it.

Build the skills behind your next automation
A useful first script reveals a clear next step: stronger functions, better file handling, more confident table processing or clearer error messages.
For broader context on analysis tools, read SQL, Python, Power BI: Skills Germany Wants.
The Python Programming Bootcamp (Data Analysis & Automation) covers programming foundations, structured files, pandas analysis and automation. These ten exact examples and every named library are not confirmed course assignments or syllabus items.