问题描述
假设我有一个包含子文件夹project1,project2,project3,...
的文件夹。
在每个项目中,我都有固定命名为process
,progress
和session
的子文件夹,在这些子文件夹中,还有其他子文件夹和图像文件。
现在,我想为每个files1
创建子文件夹project
,以从process
移动所有图像,并创建files2
从progress
移动所有图像}和session
。
请注意,每个项目的图像名称都是唯一的,因此我们将忽略图像名称重复的问题。
为files1
创建project1
时,我使用:
import os
dirs = './project1/files1'
if not os.path.exists(dirs):
os.makedirs(dirs)
但是我需要遍历所有项目文件夹。
我们如何在Python中做到这一点?真诚的感谢。
解决方法
为每个file1
创建file2
和project
:
# Remove non-images files
base_dir = './'
for root,dirs,files in os.walk(base_dir):
for file in files:
# print(file)
pic_path = os.path.join(root,file)
ext = os.path.splitext(pic_path)[1].lower()
if ext not in ['.jpg','.png','.jpeg']:
os.remove(pic_path)
print(pic_path)
# create files1 and files2
for child in os.listdir(base_dir):
child_path = os.path.join(base_dir,child)
os.makedirs(child_path + '/file1',exist_ok=True)
os.makedirs(child_path + '/file2',exist_ok=True)