Fundamentals 6 min read

Auto‑Copy Important Files from a USB Drive with a Simple Python Script

This tutorial shows how to write a lightweight Python program that runs in the background, detects when a USB drive is mounted, and automatically copies selected files—filtered by type, size, or modification date—to a local folder, illustrating core file‑handling techniques.

MaGe Linux Operations
MaGe Linux Operations
MaGe Linux Operations
Auto‑Copy Important Files from a USB Drive with a Simple Python Script

How to Detect USB Insertion?

On macOS/Linux a USB drive is mounted under the /Volumes directory. By periodically scanning this directory you can detect when a new folder appears, indicating that a USB has been inserted.

How to Selectively Copy Files?

After confirming insertion, you may want to copy only certain files—e.g., documents, presentations, or files smaller than a given size—while ignoring large media files.

Recursively Traversing Files with os.walk

The os.walk function walks through a directory tree, yielding each directory and file, which allows you to examine every file on the USB.

Copying Files with shutil

The shutil.copy2 function copies a file while preserving metadata. Combined with os.path.getsize you can filter files by size (e.g., only copy files smaller than 3 MiB).

Filtering by Extension with Regular Expressions

Import the re module and use a regular expression to match desired file extensions such as .docx or .ppt. This lets you skip unwanted media files.

Filtering by Modification Time

By checking a file’s modification timestamp you can copy only files that were recently added or changed, which is useful for incremental backups.

All of the above logic can be combined into a short Python script that runs in the background, sleeps for a few seconds between scans, and automatically copies selected files from any newly inserted USB drive to a target directory. The example was tested on macOS; it works similarly on Linux and can be adapted for Windows with minor changes.

PythonUSBshutilfile copyos.walk
MaGe Linux Operations
Written by

MaGe Linux Operations

Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.

0 followers
Reader feedback

How this landed with the community

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.