python自动复制u盘中的文件
#复制指定目录中的文件到save目录
import re,os,shutil,time
#遍历u盘
def get_filelist(path):
Filelist = []
for home, dirs, files in os.walk(path):
for filename in files:
# 文件名列表,包含完整路径
# Filelist.append(os.path.join(home, filename))
# 文件名列表,只包含文件名
if reg_test(filename):
Filelist.append(os.path.join(home, filename))
return Filelist
#匹配后缀名
def reg_test(file):
#匹配条件为后缀名时txt,docx,pptx,zip,jpg(可以自己添加其他后缀名)
regex_filename = re.compile(r'(.*txt$)|(.*dcox$)|(.*pptx$)|(.*zip$)|(.*jpg$)')
#匹配后缀名
if regex_filename.match(file):
return True
if __name__ == "__main__":
#u盘目录
path = 'G:'
while True:
#判断是否存在G盘
if (os.path.exists(path)):
Filelist = get_filelist(path)
#保存的目录
copy_floder_path = os.path.join('D:\\copy_floder',time.strftime('%Y-%m-%d %H-%M', time.localtime()))
os.mkdir(copy_floder_path)
#复制文件
for file in Filelist:
shutil.copy(file, copy_floder_path)
break
运行起来,只要U盘一插入电脑就会进行复制。