python从当前文件夹中,遍历每个文件夹找到包括find_key的文件夹,剪切到dst_dir路径中

 

复制代码
import os
import shutil

def move_dir(src_dir=None, dst_dir='new_dir', find_key='case_data_stub.json'):
    '''
    从当前文件夹中,遍历每个文件夹,
    找到包括find_key的文件夹,剪切到dst_dir路径中
    '''
    find_num = 0
    cur_path = os.getcwd()
    print("当前路径:", cur_path)
    dst_dir = os.path.join(cur_path, dst_dir)
    print("目的路径:", dst_dir)
    for dirpath, dirnames, filenames in os.walk(cur_path):
        for dirname in dirnames:
            full_path = os.path.join(dirpath, dirname)
            if os.path.isfile(full_path):
                continue
            # 到此,得到了完整的路径,full_path
            for file in os.listdir(full_path):
                if os.path.isfile(os.path.join(full_path, file)):
                    if file == find_key and dst_dir not in full_path:
                        find_num += 1  # 找到的个数+1
                        print("找到了find_key, full_path: ", full_path)
                        if os.path.exists(dst_dir):
                            # 如果文件夹已存在,先删除,再创建
                            print("文件夹已存在,先删除,再创建: ", dst_dir)
                            shutil.rmtree(dst_dir)
                            os.mkdir(dst_dir)
                        else:
                            print("文件夹不存在, 创建文件夹: ", dst_dir)
                            os.mkdir(dst_dir)
                        shutil.move(full_path, dst_dir)

    return find_num

if __name__ == '__main__':
    find_num = move_dir(dst_dir='new_dir')
    print("找到了多少个:", find_num)
复制代码

 

posted @   胖白白  阅读(61)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
历史上的今天:
2021-11-01 整数的溢出或回绕
2020-11-01 串口通信+进制基础+位运算
点击右上角即可分享
微信分享提示