我正在尝试将数据集的体系结构重组为另一个方便的结构。
采用以下架构:
Dataset/A/0000/left/
Dataset/A/0000/right/
Dataset/A/0001/left/
Dataset/A/0001/right/
.
.
Dataset/A/0750/left/
Dataset/A/0750/right/
Dataset/B/0000/left/
Dataset/B/0000/right/
Dataset/B/0001/left/
Dataset/B/0001/right/
.
.
Dataset/B/0750/left/
Dataset/B/0750/right/
我如何将所有“左”和“右”子文件夹收集到单独的目录中,并将它们重命名为具有以下架构:
Dataset/left/0000 ### A sub-folder
Dataset/left/0001
.
.
Dataset/left/0750
Dataset/left/0751 ### B sub-folder
Dataset/left/0752
.
.
Dataset/left/1500
答案 0 :(得分:0)
这应该做到:
import os
import shutil
try:
# Mock the problem
for i in range(750):
os.makedirs("Dataset/A/0{}/left".format(i), )
os.makedirs("Dataset/A/0{}/right".format(i))
os.makedirs("Dataset/B/0{}/left".format(i))
os.makedirs("Dataset/B/0{}/right".format(i))
os.mkdir("./Dataset/left")
os.mkdir("./Dataset/right")
except FileExistsError as e:
pass
# See pythoncentral.io/how-to-recursively-copy-a-directory-folder-in-python/
def copyDirectory(src, dest):
try:
shutil.copytree(src, dest)
# Directories are the same
except shutil.Error as e:
pass
# Any error saying that the directory doesn't exist
except OSError as e:
pass
def move(sub):
for file, subfolder, folder in os.walk(sub):
if file.split("/")[-1] in ["right", "left"]:
src = file
dest = "./Dataset/{}/{}".format(
file.split("/")[-1],
file.split("/")[-2]
)
copyDirectory(src, dest)
move("./Dataset/A")
move("./Dataset/B")
从本质上讲,此脚本的作用是:A)创建文件树的原型,B)定义复制目录的函数,C)定义函数move
,以遍历目标子文件夹并从中应用该函数B