简体   繁体   中英

How to recursively copy all files with a certain extension in a directory using Python?

I'm trying to write a Python function that copies all .bmp files from a directory and its sub-directories into a specified destination directory.

I've tried using os.walk but it only reaches into the first sub-directory and then stops. Here's what I have so far:

def copy(src, dest):

    for root, dirs, files in os.walk(src):
        for file in files:
            if file[-4:].lower() == '.bmp':
                shutil.copy(os.path.join(root, file), os.path.join(dest, file))

What do I need to change so it copies every .bmp file from every sub-directory?

EDIT: This code actually does work, there were just fewer bitmap files in the source directory than anticipated. However, for the program I am writing, I prefer the method using glob shown below.

If I understand correctly, you want glob with recursive=True , which, with the ** specifier, will recursively traverse directories and find all files satisfying a format specifier:

import glob
import os
import shutil

def copy(src, dest):
    for file_path in glob.glob(os.path.join(src, '**', '*.bmp'), recursive=True):
        new_path = os.path.join(dest, os.path.basename(file_path))
        shutil.copy(file_path, new_path)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM