先上代码:
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# author : jin time :2019/3/5
#可以指定文件的格式与大小
import os, time, shutil, re
#识别文件的格式
regex_filename = re.compile(r'(.*zip$)|(.*rar$)|(.*docx$)|(.*ppt$)|(.*xlx$)|(.*py$)')
def usb_monitor(sleep_time, usb_path, copy_folder):
if not os.path.exists(copy_folder):
os.mkdir(copy_folder)
a = 0
while True:
time.sleep(sleep_time)
start_time = time.time()
file_num = 0
try:
u = os.listdir(usb_path) #用于返回指定的文件夹包含的文件或文件夹的名字的列表
except FileNotFoundError:
print('usb is not found')
a = 0
continue
if a > 0:
print('usb has already copied')
break
copy_folder1 = os.path.join(copy_folder, time.strftime('%Y-%m-%d %H-%M', time.localtime()))
os.mkdir(copy_folder1)
# root为当前正在遍历的这个文件夹的本身的地址
# dirs是一个list,内容是该文件夹中所有目录的名字(不包含子目录)
# files同样是list,内容是该文件夹中的所有的文件(不包含子目录)
for root, dirs, files in os.walk(usb_path):
if a == 0:
print('start copy usb is {}'.format(dirs[0]))
usb_name = dirs[0]
a += 1
if len(files) == 0:
continue
for name in files:
file = os.path.join(root, name)
if regex_filename.match(file) and os.path.getsize(file) < 1024*1024*2: #字节大小(转化为2M)
file_num += 1
print(file)
file_create_time = time.strftime('%Y-%m-%d %H-%M-%S', time.localtime(os.path.getctime(file))) #输出文件创建时间
shutil.copy2(file, copy_folder1) #复制file到copy_folder1中,并且复制文件的权限位
else:
continue
if file_num == 0:
print('usb is not found file')
continue
print('共下载{}份文件---用时:{}s'.format(file_num, time.time()-start_time))
if __name__ == '__main__':
usb_monitor(1, 'F:\\', 'save_path')
这个程序要注意以下几点:
os 文件目录操作
shutil 高级文件目录处理
re 正则匹配
time
pyinstaller 打包
这些是要运用到的模块↑↑
它能指定文件格式和具体大小,在假期可以用它来看看朋友的U盘里到底有什么不为人知的秘密了😏