Automate Your Files: A Python Script to Sort Anything by Extension
This tutorial walks you through building a Python script that scans a given directory, extracts all files, and automatically organizes them into separate folders based on their file extensions, demonstrating practical use of the os, glob, and shutil standard libraries.
Hello everyone, it’s time for a Python office‑automation topic.
This article shares the implementation of a file‑organization script. Given a directory, the script extracts all files and categorizes them into folders according to their extensions, as illustrated below.
Through this example you can learn the combined use of three standard libraries: os, glob, and shutil.
First import the required libraries:
import os
import shutil
import globThe os library can perform many operating‑system level operations such as creating, moving, renaming, and deleting folders. The shutil library complements it for copying and moving files. The glob library uses wildcards to search for files.
Set the paths for the classification folder and the target folder, then ensure the classification folder exists:
mkdir_path = r'C:\Users\chenx\文件夹分类'
goal_dir = r'C:\xxxxxxxx'
if not os.path.exists(mkdir_path):
os.mkdir(mkdir_path)Iterate over all files using glob.glob with the recursive flag, determine each file’s extension, create a corresponding folder if it does not exist, and copy the file there:
for file in glob.glob(f'{goal_dir}/**/*', recursive=True):
if os.path.isfile(file):
filename = os.path.basename(file)
if '.' in filename:
suffix = filename.split('.')[-1]
else:
suffix = 'others'
if not os.path.exists(f'{mkdir_path}/{suffix}'):
os.mkdir(f'{mkdir_path}/{suffix}')
dir_num += 1
shutil.copy(file, f'{mkdir_path}/{suffix}')
file_num += 1
print(f'整理完成,有{file_num}个文件分类到了{dir_num}个文件夹中')The following screenshot shows a typical error when a file without an extension is processed incorrectly:
Python Crawling & Data Mining
Life's short, I code in Python. This channel shares Python web crawling, data mining, analysis, processing, visualization, automated testing, DevOps, big data, AI, cloud computing, machine learning tools, resources, news, technical articles, tutorial videos and learning materials. Join us!
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
