品网站建设公司排名,网业浏览设置在哪,大连做企业网站哪家好,网站建设终端是什么USB驱动器作为常见的数据存储设备#xff0c;经常用于数据传输和备份。 然而#xff0c;我们在手动处理文件复制可能效率低下且容易出错。 因此#xff0c;我们可以利用Python编写脚本来自动化这一过程#xff0c;提高效率和数据安全性。
准备工作
首先#xff0c;我们需…USB驱动器作为常见的数据存储设备经常用于数据传输和备份。 然而我们在手动处理文件复制可能效率低下且容易出错。 因此我们可以利用Python编写脚本来自动化这一过程提高效率和数据安全性。
准备工作
首先我们需要安装Python以及几个必要的库os、shutil、time和psutil。这些库将帮助我们实现文件操作、定时和系统监测功能。
获取硬盘驱动器列表
这段代码利用psutil库获取系统中可移动的磁盘驱动器列表例如USB驱动器。import psutildef get_disk_drives():disk_partitions psutil.disk_partitions(allFalse)drives [partition.device.upper() for partition in disk_partitions if partition.fstype ! and removable in partition.opts]return drives文件拷贝功能
这段代码定义了一个函数用于将指定文件类型.jpg、.png、.txt从USB驱动器拷贝到指定目标文件夹。
它确保在复制过程中限制了数据传输的速度避免过载系统。import os
import shutildef 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_okTrue)with open(src_file, rb) as fsrc:with open(dst_file, wb) as fdst:shutil.copyfileobj(fsrc, fdst, lengthspeed_limit_kb * 1024)检查新插入的USB驱动器
此函数定期检查新插入的USB驱动器并调用文件拷贝函数将特定文件类型复制到预定目标文件夹。
它通过在列表中记录已知驱动器来避免重复操作。import timedef check_for_new_drive(speed_limit_kb10240):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(fNew drive detected: {new_drive})time.sleep(3) # 等待3秒后再开始拷贝copy_ppt_files(new_drive, destination_drive, speed_limit_kb)主程序
主程序初始化了已知驱动器列表和目标路径并通过调用check_for_new_drive函数来持续检查新插入的USB驱动器。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秒检查一次