码迷,mamicode.com
首页 > 编程语言 > 详细

Python脚本:linux上将筛选的文件夹复制到另一个目录,保存目录结构

时间:2019-01-03 21:43:34      阅读:235      评论:0      收藏:0      [点我收藏+]

标签:make   目录结构   join   where   new   and   cms   三层   time   

import os,shutil

def newDir(dir_path):
    if not os.path.exists(dir_path):
        os.makedirs(dir_path)

def copydir(where_path,go_path,start_time,end_time):
    newDir(go_path)
    for brand in os.listdir(where_path):
        brand_path = os.path.join(where_path, brand)
        #print(‘brand_path‘,brand_path)
        for site in os.listdir(brand_path):
            site_path = os.path.join(brand_path,site)
            #print(‘site_path‘,site_path)
            for child in os.listdir(site_path):
                file_time = ‘-‘.join(child.split(‘-‘)[2:5])
                go_dir = go_path + ‘/‘ + brand + ‘/‘ + site#动态生成子目录
                print(file_time[:10])
                if file_time[:10] >= start_time and file_time[:10] <= end_time:
                    child_path = os.path.join(site_path,child)

                    if not os.path.isdir(child_path):
                        #print(‘file‘,child_path)
                        newDir(go_dir)
                        shutil.copy(child_path,go_dir)
                    else:
                        #print(‘dir‘,child_path)
                        #复制文件夹能够自己生成目录
                        shutil.copytree(child_path,go_dir+‘/‘+child)

#删除文件名包含2018的文件和文件夹
def deldir(path):
    for child in os.listdir(path):
        child_path = os.path.join(path,child)
        if ‘2018‘ in child:
            if not os.path.isdir(child_path):
                os.unlink(child_path)
            else:
                shutil.rmtree(child_path)

if __name__ == "__main__":
    copydir(‘/lingtian/static_files/mkcms_dev/memo/memo_htmls‘,‘/lingtian/static_files/mkcms_dev‘,‘2018-09-01‘,‘2018-09-30‘)
    #deldir(‘/lingtian/static_files/mkcms_dev‘)                            

 我要复制的目录三层,所以有三层循环,保留了原来的目录结构

Python脚本:linux上将筛选的文件夹复制到另一个目录,保存目录结构

标签:make   目录结构   join   where   new   and   cms   三层   time   

原文地址:https://www.cnblogs.com/lelexiu/p/10216837.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!