user2988464
user2988464

Reputation: 3461

Python: Copy files with specific extension in a tree of directory

I need to copy files with extension of .jpg from a folder tree. The folder tree is like this:

-folder_A
    -folder_1
        -1.txt
        -1.jpg
    -folder_2
        -2.txt
        -2.jpg
    -folder_3
        -3.txt
        -4.jpg
-folder_B

How can I copy all the x.jpg to folder_B? i.e. All the files are the same in folder_A, and in folder_B, files are 1.jpg, 2.jpg...

Upvotes: 0

Views: 2068

Answers (2)

Lioman
Lioman

Reputation: 535

Or if you know your OS you can just execute the according shell-command. (But I think the solution of @stellasia is cleaner)

Example (Linux):

import os

os.system('cp -r folder_A/*/*.jpg folder_B/')

Upvotes: 0

stellasia
stellasia

Reputation: 5612

Have a look at the python os module.

import os
import shutil as sh

root_path = "./folder_A"
dest_path = "./folder_B"

for dirpath, dnames, fnames in os.walk(root_path):    
    for f in fnames:
        if f.endswith(".jpg"):
            source_file_path =  os.path.join(dirpath, f)
            dest_file_path   =  os.path.join(dest_path, f)
            sh.copyfile(source_file_path, dest_file_path)

Upvotes: 2

Related Questions