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

 

保持原有目录结构

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

sourcefolder='E:/source/'
desfolder='E:/destination/'
filelist=GetExtNamesList(all_path(sourcefolder),'.htm')#此处例子是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)#如果要改为移动,而不是拷贝,可以将copy改为move

 

 一个函数也可以,更简洁

def get_files_with_extension(folder_path, extension):
    file_list = []
    for root, dirs, files in os.walk(folder_path):
        for file in files:
            if file.endswith(extension):
                file_list.append(os.path.join(root, file))
    return file_list

 

posted @ 2018-11-07 14:43  重积德  阅读(3168)  评论(0编辑  收藏  举报