使用Python實現(xiàn)USB自動復制文件
USB驅動器作為常見的數(shù)據(jù)存儲設備,經常用于數(shù)據(jù)傳輸和備份。
然而,我們在手動處理文件復制可能效率低下且容易出錯。
因此,我們可以利用Python編寫腳本來自動化這一過程,提高效率和數(shù)據(jù)安全性。
準備工作
首先,我們需要安裝Python以及幾個必要的庫:os、shutil、time和psutil。這些庫將幫助我們實現(xiàn)文件操作、定時和系統(tǒng)監(jiān)測功能。
獲取硬盤驅動器列表
這段代碼利用psutil庫獲取系統(tǒng)中可移動的磁盤驅動器列表,例如USB驅動器。
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
文件拷貝功能
這段代碼定義了一個函數(shù),用于將指定文件類型(.jpg、.png、.txt)從USB驅動器拷貝到指定目標文件夾。
它確保在復制過程中限制了數(shù)據(jù)傳輸?shù)乃俣?,避免過載系統(tǒng)。
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驅動器
此函數(shù)定期檢查新插入的USB驅動器,并調用文件拷貝函數(shù)將特定文件類型復制到預定目標文件夾。
它通過在列表中記錄已知驅動器來避免重復操作。
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函數(shù)來持續(xù)檢查新插入的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秒檢查一次到此這篇關于使用Python實現(xiàn)USB自動復制文件的文章就介紹到這了,更多相關Python USB復制文件內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
python神經網(wǎng)絡Inception?ResnetV2模型復現(xiàn)詳解
這篇文章主要為大家介紹了python神經網(wǎng)絡Inception?ResnetV2模型復現(xiàn)詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-05-05
python openCV實現(xiàn)攝像頭獲取人臉圖片
這篇文章主要為大家詳細介紹了python openCV實現(xiàn)攝像頭獲取人臉圖片,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2020-08-08
Django 創(chuàng)建后臺,配置sqlite3教程
今天小編就為大家分享一篇Django 創(chuàng)建后臺,配置sqlite3教程,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-11-11
python采用requests庫模擬登錄和抓取數(shù)據(jù)的簡單示例
這篇文章主要介紹了python采用requests庫模擬登錄和抓取數(shù)據(jù)的簡單示例,代碼簡單卻功能強大!需要的朋友可以參考下2014-07-07

