python3拷贝指定文件类型到另外一个文件夹

时间:2022-01-07 09:54:21

 

保持原有目录结构

import os,shutil

def all_path(dirname):
    result = []
    for maindir, subdir, file_name_list in os.walk(dirname):
        for filename in file_name_list:
            apath = os.path.join(maindir, filename)
            result.append(apath)
    return result

def GetExtNamesList(fileslist,ext):
    filenames=[]
    for file in fileslist:
        fileinfo=os.path.splitext(file)
        if fileinfo[1]==ext:
            filenames.append(file)
    return filenames

result=''
sourcefolder='E:/source/'
desfolder='E:/destination/'
filelist=GetExtNamesList(all_path(sourcefolder),'.htm')
for file in filelist:
    print(file)
    desfilename=file.replace('\\','/').replace(sourcefolder,desfolder)
    print(desfilename)
    if not os.path.exists(os.path.dirname(desfilename)):
        os.makedirs(os.path.dirname(desfilename))
    if not os.path.exists(desfilename):
        shutil.copy(file,desfilename)