Detecting USB Insertion and Selectively Copying Files with Python
This article explains how to monitor the /Volumes directory on macOS to detect USB insertion, then uses Python's os, shutil, and re modules to recursively walk the USB file system, filter files by type, size, and modification time, and automatically copy selected files to a local folder.
How to Detect USB Insertion
By periodically scanning the /Volumes directory (e.g., every three seconds with time.sleep(3) ), a Python script can detect when a new folder appears, which indicates that a USB drive has been mounted.
How to Selectively Copy Files
The script can be extended to copy only important files—such as .docx or .ppt —while skipping large media files, by applying filters based on file extension, size, or modification date.
os.walk Recursively Traverses Directories
Using os.walk allows the program to walk through every sub‑directory on the USB drive, listing all files for further processing.
shutil Module for File Operations
The shutil.copy2 function copies a file while preserving metadata; it can be used to move selected files to a target directory on the host machine.
os.path.getsize() to Check File Size
os.path.getsize(filename) returns the size in bytes; the script can convert this to megabytes (e.g., 3 MB = 3 × 1024 × 1024 bytes) and skip files larger than a defined threshold.
Specifying File Types with Regular Expressions
Importing the re module enables pattern matching for file extensions, allowing the script to copy only files that match expressions such as .*\.(docx|ppt|pdf)$ .
Filtering by Modification Time
By checking each file's modification timestamp, the program can copy only files that were created or modified within a recent period, which is useful for backing up newly added documents.
The article concludes with an invitation for readers to share the tutorial publicly.
Python Programming Learning Circle
A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.
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.