0
点赞
收藏
分享

微信扫一扫

python 多文件夹中按条件复制到新的文件夹并重命名

转角一扇门 2022-02-12 阅读 89

在这里插入图片描述

import shutil
import os

def read_file_path(path):
    # 读取文件名
    return [i for i in os.listdir(path)]

def mkdir(path):
    # 创建文件夹
    import os
    path = path.strip()
    path = path.rstrip("\\")
    isExists = os.path.exists(path)
    if not isExists:
        os.makedirs(path)
        # print (path+' 创建成功')
        return True
    else:
        # print(path+' 目录已存在')
        return False

def copy_file_rename(old_path, new_path):
    # 复制文件到指定地址
    try:
        shutil.copy(old_path, new_path)
    except Exception as e:
        print(e)

def res(path_list):
    label = 0
    for i in path_list:
        file_list = read_file_path(i)
        for j in file_list:
            old_path = f"{i}/{j}"
            mkdir(r'res/train{}'.format(j.split(".")[0]))
            if label == 0:
                new_path = r'res/train{}'.format(j.split(".")[0]) + "/t0.tif"
            elif label == 1:
                new_path = r'res/train{}'.format(j.split(".")[0]) + "/t1.tif"
            else:
                new_path = r'res/train{}'.format(j.split(".")[0]) + "/label.png"
            copy_file_rename(old_path, new_path)
        label += 1

# 顺序别放错了,不然就出错了
res(["2010", "2011", "label"])

举报

相关推荐

0 条评论