Operations 5 min read

Python Script for Detecting USB Insertion and Selectively Copying Files

This tutorial explains how to create a Python program that runs in the background, monitors the /Volumes directory for newly mounted USB drives, and automatically copies only selected files based on size, type, or modification date to a local folder.

Python Programming Learning Circle
Python Programming Learning Circle
Python Programming Learning Circle
Python Script for Detecting USB Insertion and Selectively Copying Files

The article demonstrates a Python solution that continuously monitors the system for USB insertion and automatically copies important files without user interaction.

On macOS (and similarly on Linux), a newly inserted USB drive is mounted under the /Volumes directory; the script uses time.sleep(3) to poll this directory every few seconds and detects new folders as indicators of USB insertion.

File selection is performed by traversing the USB directory tree, using os.path.getsize() to filter out files larger than a specified threshold (e.g., 3 MB) and applying regular expressions to match desired extensions such as .docx or .ppt . The script can also filter files based on their last modification time.

Qualified files are copied to a target location with the shutil.copy2 (or shutil.copytree ) functions, preserving metadata. The example includes screenshots of the directory structure and the copy operation.

Additional sections cover using the shutil module for various copy operations, employing regex for more complex file‑type specifications, and selecting files by modification date to copy only recent or specific‑period files.

In conclusion, the piece emphasizes that this small program showcases Python's powerful file‑handling capabilities, works on macOS and Linux, and can be adapted for Windows with minor changes.

OSregexshutilfile handlingusb detection
Python Programming Learning Circle
Written by

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.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.