Under the file path D:/src, I have images folders and its subfolders which have a regular structure as follows:
JavaScript
x
15
15
1
Folder A
2
- Subfolder a
3
- Subfolder b
4
- Subfolder c
5
Folder B
6
- Subfolder a
7
- Subfolder b
8
- Subfolder c
9
- Subfolder d
10
Folder C
11
- Subfolder a
12
- Subfolder b
13
- Subfolder c
14
15
I want to copy all .jpg files in Subfolder b from Folder A, B, C and so on to a new folder Subfolder b in D:/dst. How can I do it in Python? Thanks.
JavaScript
1
6
1
Subfolder b
2
-xxx.jpg
3
-xyx.jpg
4
-yxz.jpg
5
6
Here is what I have found from the following link may helps:
Copy certain files from one folder to another using python
JavaScript
1
16
16
1
import os;
2
import shutil;
3
import glob;
4
5
source="C:/Users/X/Pictures/test/Z.jpg"
6
dest="C:/Users/Public/Image"
7
8
if os.path.exists(dest):
9
print("this folder exit in this dir")
10
else:
11
dir = os.mkdir(dest)
12
13
for file in glob._iglob(os.path.join(source),""):
14
shutil.copy(file,dest)
15
print("done")
16
Advertisement
Answer
Try this
JavaScript
1
14
14
1
import os
2
from os.path import join, isfile
3
4
BASE_PATH = 'd:/test'
5
SUBFOLDER = 'Subfolder b'
6
7
for folder, subfolders, *_ in os.walk(BASE_PATH):
8
if SUBFOLDER in subfolders:
9
full_path = join(BASE_PATH, folder, SUBFOLDER)
10
files = [f for f in os.listdir(full_path) if isfile(join(full_path, f)) and f.lower().endswith(('.jpg', '.jpeg'))]
11
for f in files:
12
file_path = join(full_path, f)
13
print (f'Copy {f} somewehere')
14