Python File Organizer Script Example
This beginner-friendly example shows how to organize files in a folder by moving them into subfolders based on file type.
The goal of this page is to help you understand one practical Python script. It is not a full guide to every file-handling function in Python.
Quick example
from pathlib import Path
import shutil
source_folder = Path("downloads")
folders = {
".jpg": "images",
".png": "images",
".gif": "images",
".txt": "text_files",
".pdf": "pdf_files",
".csv": "csv_files",
}
for item in source_folder.iterdir():
if item.is_file():
extension = item.suffix.lower()
folder_name = folders.get(extension, "other")
destination_folder = source_folder / folder_name
destination_folder.mkdir(exist_ok=True)
shutil.move(str(item), str(destination_folder / item.name))
print("Files organized.")
This example organizes files inside a folder named downloads. It groups files by extension and puts unknown file types into an other folder.
What this example does
This script:
- Shows a complete beginner-friendly script
- Moves files into folders based on file extension
- Uses simple rules like
.jpg -> imagesand.pdf -> pdf_files - Helps you understand a real automation task
If you are new to folders and paths in Python, it may also help to read working with file paths in Python.
What you need before running it
Before you run the script, make sure you have:
- Python installed on your computer
- A folder with files to organize
- Basic understanding of variables, loops, and
ifstatements - A test folder to practice with first
Using a test folder is important. This script moves files, so your original folder contents will change.
How the script works step by step
Here is the same script again:
from pathlib import Path
import shutil
source_folder = Path("downloads")
folders = {
".jpg": "images",
".png": "images",
".gif": "images",
".txt": "text_files",
".pdf": "pdf_files",
".csv": "csv_files",
}
for item in source_folder.iterdir():
if item.is_file():
extension = item.suffix.lower()
folder_name = folders.get(extension, "other")
destination_folder = source_folder / folder_name
destination_folder.mkdir(exist_ok=True)
shutil.move(str(item), str(destination_folder / item.name))
print("Files organized.")
Step by step, it does this:
- Imports
Pathfrompathlibto work with file paths - Imports
shutilso it can move files - Sets
source_folderto the folder you want to organize - Creates a dictionary that maps file extensions to folder names
- Loops through each item in the source folder
- Checks that the item is a file, not a folder
- Reads the file extension with
suffix.lower() - Chooses a destination folder with
folders.get() - Creates that folder if it does not already exist
- Moves the file into the correct folder
If you want to learn more about listing folder contents, see how to list files in a directory in Python.
Important lines to explain
source_folder = Path("downloads")
source_folder = Path("downloads")
This creates a path object for the folder named downloads.
If that folder is not in the same location as your script, you may need a full path instead, such as:
source_folder = Path("/Users/yourname/Downloads")
if item.is_file():
if item.is_file():
This checks whether the current item is a file.
It skips subfolders. That matters because this script is only meant to organize files directly inside the source folder.
item.suffix.lower()
extension = item.suffix.lower()
This gets the file extension and changes it to lowercase.
That helps with files like:
photo.jpgphoto.JPGphoto.Jpg
All of these become .jpg, so they match the same rule.
folders.get(extension, "other")
folder_name = folders.get(extension, "other")
This looks up the extension in the dictionary.
- If the extension exists, it uses the matching folder name
- If the extension is not found, it uses
"other"
So a file like report.pdf goes to pdf_files, but a file like archive.zip goes to other.
destination_folder.mkdir(exist_ok=True)
destination_folder.mkdir(exist_ok=True)
This creates the destination folder if needed.
The exist_ok=True part prevents an error if the folder already exists. If you need more help creating folders, see how to create a directory in Python.
shutil.move(...)
shutil.move(str(item), str(destination_folder / item.name))
This moves the file to its new location.
The file is removed from the original place and placed in the destination folder.
Expected result
After the script runs, your folder may look something like this:
downloads/images/downloads/pdf_files/downloads/text_files/downloads/csv_files/downloads/other/
Files are sorted into folders automatically, which makes the original folder easier to browse.
Ways to customize the script
You can change the script in several simple ways:
- Add more file extensions to the dictionary
- Change folder names to fit your own system
- Organize by first letter, date, or filename pattern instead of extension
- Print each move so you can see what changed
For example, this version prints each file move:
from pathlib import Path
import shutil
source_folder = Path("downloads")
folders = {
".jpg": "images",
".png": "images",
".gif": "images",
".txt": "text_files",
".pdf": "pdf_files",
".csv": "csv_files",
}
for item in source_folder.iterdir():
if item.is_file():
extension = item.suffix.lower()
folder_name = folders.get(extension, "other")
destination_folder = source_folder / folder_name
destination_folder.mkdir(exist_ok=True)
destination_path = destination_folder / item.name
print(f"Moving {item.name} -> {destination_path}")
shutil.move(str(item), str(destination_path))
print("Files organized.")
Example output:
Moving photo.JPG -> downloads/images/photo.JPG
Moving notes.txt -> downloads/text_files/notes.txt
Moving report.pdf -> downloads/pdf_files/report.pdf
Files organized.
Safety tips for beginners
Be careful when testing a file-moving script.
Good habits:
- Run the script on a copy of your files first
- Test with a small folder before using a large one
- Check that the folder path is correct before running
- Watch out for files that have the same name
If you want to make changes without moving files yet, you can temporarily replace the shutil.move(...) line with a print(...) line. That lets you preview what would happen.
Common problems
A few problems are common with scripts like this.
FileNotFoundError
This happens if the source folder does not exist.
Common causes:
- Using the wrong folder path
- Running the script from a different working directory than expected
Useful checks:
print(source_folder.resolve())
print(source_folder.exists())
If you need help with this error, see FileNotFoundError: No such file or directory.
PermissionError
This happens if Python cannot access the folder or move the files.
Common causes:
- Trying to move files without permission
- Using a protected system folder
If needed, see PermissionError: Permission denied.
Files with uppercase extensions
Some files may use extensions like .JPG instead of .jpg.
That is why the script uses:
item.suffix.lower()
Without .lower(), some files would not match your dictionary rules.
Duplicate file names
If two files with the same name are moved into the same folder, one may overwrite the other.
For example:
downloads/photo.jpg- another
photo.jpgfrom somewhere else later
A safer version would check whether the destination file already exists before moving.
Files with no extension
Some files do not have an extension at all.
In this script, those files will go into the other folder because they do not match any key in the dictionary.
Common mistakes to check
If the script is not working as expected, these checks can help:
print(source_folder.resolve())
print(item.name)
print(item.suffix.lower())
print(destination_folder)
print(source_folder.exists())
These print statements help you see:
- The full folder path Python is using
- Each file name being processed
- The extension Python reads
- The destination folder for that file
- Whether the source folder actually exists
Common causes of problems include:
- Using the wrong folder path
- Running the script in a different working directory than expected
- Trying to move files without permission
- Forgetting that extensions can be uppercase like
.JPG - Not handling duplicate file names in destination folders
FAQ
Does this script move files or copy them?
It moves files. After running, the files are no longer in their original location.
Can I organize files by type without using pathlib?
Yes. You can use os and os.path, but pathlib is usually easier for beginners to read. If you want a broader overview, see the Python os module overview.
What happens to files with unknown extensions?
In this example, they go into the other folder.
Will this script organize files inside subfolders too?
No. This version only looks at items directly inside the source folder.
How can I avoid overwriting files with the same name?
Add a check before moving. Rename the file or skip it if the destination already exists. You may also want to learn how to rename a file in Python.
See also
- How to list files in a directory in Python
- Working with file paths in Python
- Python os module overview
- os.path.join() function explained
- FileNotFoundError: No such file or directory
- PermissionError: Permission denied
- How to rename a file in Python
- How to create a directory in Python
Try changing this example for your own Downloads folder, or build a safer version that copies files instead of moving them.