Automate with Python: Scripts to Rename and Organise Files
Three ready-to-use Python scripts to tidy up the Downloads folder, batch-rename files and archive old files, with scheduled execution on Windows and Linux.
One of the most useful things you can do with Python, even as a beginner, is automate repetitive work on files: tidying up a folder full of documents, renaming hundreds of photos, moving things you no longer need into an archive. These are jobs that take hours by hand and a few seconds with a script.
In this guide you will find three complete scripts, ready to copy and adapt, and instructions for making them run on their own at regular intervals.
Before you start: three safety rules
A script that moves or renames files works fast, even when it gets things wrong. That is why all the scripts in this guide follow three rules:
- Dry-run mode: each script has a
DRY_RUNvariable. As long as it isTrue, the script only shows what it would do, without touching anything. Always do a dry run first and check the list. - No overwriting: if a file with the same name already exists at the destination, the script adds a number to the name instead of overwriting it.
- No deleting: files are moved, never deleted.
Before using a script on an important folder, try it on a copy anyway.
The tool: pathlib
To work with files and folders we use pathlib, a module included with Python: there is nothing to install. It represents every path as an object with handy properties:
from pathlib import Path
file = Path.home() / "Documents" / "report.pdf"
print(file.name) # report.pdf
print(file.stem) # report
print(file.suffix) # .pdf
print(file.parent) # the Documents folder
print(file.exists()) # True if the file exists
The / operator joins the parts of the path and works the same way on Windows and Linux. Path.home() points to your user folder.
Script 1: tidy up the Downloads folder by file type
This script splits the files in the Downloads folder into subfolders (Images, Documents, Archives and so on) based on their extension.
from pathlib import Path
import shutil
FOLDER = Path.home() / "Downloads"
DRY_RUN = True # True = only show what it would do; False = really move
CATEGORIES = {
"Images": {".jpg", ".jpeg", ".png", ".gif", ".webp", ".heic"},
"Documents": {".pdf", ".doc", ".docx", ".odt", ".txt", ".xlsx", ".pptx"},
"Archives": {".zip", ".rar", ".7z", ".tar", ".gz"},
"Audio and video": {".mp3", ".wav", ".mp4", ".mkv", ".mov"},
"Programs": {".exe", ".msi", ".deb", ".dmg"},
}
def category_for(extension):
for name, extensions in CATEGORIES.items():
if extension in extensions:
return name
return "Other"
def free_path(path):
"""If the file already exists, adds (1), (2)... to the name."""
if not path.exists():
return path
n = 1
while True:
candidate = path.with_name(f"{path.stem} ({n}){path.suffix}")
if not candidate.exists():
return candidate
n += 1
for file in list(FOLDER.iterdir()):
if not file.is_file():
continue # skip folders
folder = FOLDER / category_for(file.suffix.lower())
destination = free_path(folder / file.name)
print(f"{file.name} -> {folder.name}/{destination.name}")
if not DRY_RUN:
folder.mkdir(exist_ok=True)
shutil.move(str(file), str(destination))
How it works:
CATEGORIESmaps each subfolder to the extensions it should contain. You can add categories or extensions as you like.iterdir()lists the contents of the folder. We turn it into a list withlist()because we move files during the loop, and it is better to have the complete list from the start.suffix.lower()converts the extension to lower case, so.JPGand.jpgend up in the same place.shutil.move()moves the file, even between different drives.
Save the script as organize_downloads.py, run it once with DRY_RUN = True, check the list and, if everything looks right, change the value to False and run it again.
Script 2: batch-rename files with the date
A classic: a folder of photos or documents with unclear names, such as IMG_4521.jpg. This script adds the last-modified date to the beginning of each name, in year-month-day format, so the files sort themselves into chronological order.
from datetime import datetime
from pathlib import Path
import re
FOLDER = Path.home() / "Pictures" / "Holidays"
DRY_RUN = True
ALREADY_DATED = re.compile(r"^\d{4}-\d{2}-\d{2}_")
for file in sorted(FOLDER.iterdir()):
if not file.is_file() or ALREADY_DATED.match(file.name):
continue # skip folders and files already renamed
date = datetime.fromtimestamp(file.stat().st_mtime).strftime("%Y-%m-%d")
new = file.with_name(f"{date}_{file.name}")
n = 1
while new.exists():
new = file.with_name(f"{date}_{file.stem} ({n}){file.suffix}")
n += 1
print(f"{file.name} -> {new.name}")
if not DRY_RUN:
file.rename(new)
A few details:
st_mtimeis the file's last-modified date, provided by the operating system.- The
ALREADY_DATEDregular expression recognises names that already start with a date. This way you can run the script again without adding the date twice. strftime("%Y-%m-%d")formats the date as2026-11-12. It is the best format for file names, because alphabetical order matches chronological order.
For photos, the modification date does not always match the date the photo was taken, for example if the photos were copied from another device. In that case the exact date is in the image's EXIF metadata, which you can read with the Pillow library: a good exercise for a next step.
Script 3: archive older files
This script moves into an Archive subfolder all files that have not been modified for a certain number of days. It is useful for keeping working folders such as Downloads or Desktop tidy without losing anything.
from pathlib import Path
import shutil
import time
FOLDER = Path.home() / "Downloads"
DAYS = 90
DRY_RUN = True
limit = time.time() - DAYS * 24 * 60 * 60
archive = FOLDER / "Archive"
moved = 0
for file in list(FOLDER.iterdir()):
if file.is_file() and file.stat().st_mtime < limit:
destination = archive / file.name
n = 1
while destination.exists():
destination = archive / f"{file.stem} ({n}){file.suffix}"
n += 1
print(f"Archive: {file.name}")
moved += 1
if not DRY_RUN:
archive.mkdir(exist_ok=True)
shutil.move(str(file), str(destination))
print(f"Files to archive: {moved}")
time.time() returns the current time in seconds; subtracting 90 days expressed in seconds gives us the cut-off date. Files modified before that date are moved.
Running the scripts
The scripts only use modules included with Python, so there are no libraries to install. To run them, just open the terminal in the folder where you saved them:
# Windows
python organize_downloads.py
# Linux and macOS
python3 organize_downloads.py
To work on a different folder, change the value of FOLDER at the top of the script. On Windows you can also write a full path, preceded by the letter r to avoid problems with backslashes: FOLDER = Path(r"D:\Work\Scans").
Making them run automatically
An automation is at its best when you do not even have to remember to start it. Set DRY_RUN = False only after checking the script, then schedule it.
On Windows: Task Scheduler
- Open Task Scheduler from the Start menu and choose Create Basic Task.
- Give the task a name and choose when to run it, for example every Monday morning.
- As the action choose Start a program. In Program/script enter the full path to Python, for example
C:\Script\.venv\Scripts\python.exeif you use a virtual environment; in Add arguments type the name of the script, for exampleorganize_downloads.py; in Start in enter the script's folder, for exampleC:\Script.
For a script that should run without a window, you can use pythonw.exe, found in the same folder, instead of python.exe.
On Linux: cron
Open your user's list of scheduled tasks with crontab -e and add a line like this one, which runs the script every Monday at 9:00:
0 9 * * 1 /home/user/script/.venv/bin/python /home/user/script/organize_downloads.py >> /home/user/script/log.txt 2>&1
The final part saves the script's messages to a log file, useful for checking what was done. Always use full paths: cron does not know the folder you normally work in.
Where to go next
These three scripts are a starting point. Some ideas for extending them:
- Pass the folder as a parameter on the command line, with the
argparsemodule, instead of editing the script. - Write a log with the
loggingmodule, to keep a record of every move. - Use the photos' EXIF date with the Pillow library.
- Send a summary by email or through a messaging service, perhaps using an API.
Official sources
- pathlib — Object-oriented filesystem paths – official Python documentation
- shutil — High-level file operations – official Python documentation
- datetime — Basic date and time types – official Python documentation
- argparse — Parser for command-line options – official Python documentation
- Task Scheduler – Microsoft documentation
Share
What's Your Reaction?
Like
0
Dislike
0
Love
0
Funny
0
Angry
0
Sad
0
Wow
0