import os
import shutil
# 父文件夹
father_folder = r"H:\dataset\train\label"
# 父文件夹下所有的子文件夹
child_folders = os.listdir(father_folder)
# 目标文件夹
label = os.path.join(father_folder, "label")
if not os.path.exists(label):
os.mkdir(label)
mask = os.path.join(father_folder, "mask")
if not os.path.exists(mask):
os.mkdir(mask)
source = os.path.join(father_folder, "source")
if not os.path.exists(source):
os.mkdir(source)
label_name = os.path.join(father_folder, "label_name")
if not os.path.exists(label_name):
os.mkdir(label_name)
for folder in child_folders:
if folder[-4:] == "json":
# 所有的子文件夹
child_folder = os.path.join(father_folder, folder)
# 遍历子文件夹中所有的文件
# root 所指的是当前正在遍历的这个文件夹的本身的地址
# dirs 是一个 list ,内容是该文件夹中所有的目录的名字(不包括子目录)
# files 同样是 list , 内容是该文件夹中所有的文件(不包括子目录)
for root, dirs, files in os.walk(child_folder):
# 如果文件夹中有文件
if len(files) > 0:
for f in files:
# 分割文件名
(filename,extension) = os.path.splitext(f)
file = os.path.join(child_folder, f)
# 将文件按需求复制到目标文件夹
if filename[-5:] == "label":
shutil.copy(file, label)
elif filename[-4:] == "mask":
shutil.copy(file, mask)
elif filename[-6:] == "source":
shutil.copy(file, source)
elif filename[-11:] == "label_names":
shutil.copy(file, label_name)
else:
print(child_folder + "文件夹是空的")
python将不同文件夹中的文件分类到指定文件夹中
最新推荐文章于 2023-10-29 22:44:45 发布