複数のサブフォルダーを持つフォルダーがある場合、それぞれが同じ構造の 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)
参照関連: