如果我有一个包含多个子文件夹的文件夹,每个子文件夹都具有相同的结构 sub1、sub2 和 sub3:
├─a
│ ├─sub1
│ ├─sub2
│ └─sub3
├─b
│ ├─sub1
│ ├─sub2
│ └─sub3
└─c
├─sub1
├─sub2
└─sub3
...
我想复制sub1
,sub2
如果里面有图像文件并忽略其他子文件夹(sub3...
),同时保持目录的树结构。这是预期的结果:
├─a
│ ├─sub1
│ └─sub2
├─b
│ ├─sub1
│ └─sub2
└─c
├─sub1
└─sub2
...
我应该怎么做才能得到预期的结果?我尝试了以下代码,但它只复制sub1
,sub2
并且sub3
,我得到了TypeError: copy() takes no arguments (1 given)
。
感谢@PrasPJ。
import os
import os.path
import shutil
import fnmatch
src_dir= ['C:/Users/User/Desktop/source/input'] # List of source dirs
included_subdirs = ['sub1', 'sub2'] # subdir to include from copy
dst_dir = 'C:/Users/User/Desktop/source/output' # folder for the destination of the copy
for root_path in src_dir:
#print(root_path)
for root, dirs, files in os.walk(root_path): # recurse walking
for dir in included_subdirs:
#print(dir)
if dir in dirs:
source = os.path.join(root,dir)
f_dst = source.replace(root_path, dst_dir)
print (source, f_dst)
for file in os.listdir(source):
print(file)
if file.endswith(".jpg") or file.endswith(".jpeg"):
shutil.copytree(source, f_dst)
参考相关: