Reputation: 57
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.
Upvotes: 1
Views: 3039
Reputation: 19885
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)
Upvotes: 4