0

I am trying to organize files into specific folders by using fnmatch but for some reason the the files are not able to be moved or copied once they go through the loop I wrote. I made sure that every directory is correctly named and printed to check if my program is working which it does.

import os import shutil import fnmatch from pathlib import Path for dirpath, dirnames, files in os.walk('.'): for file_name in files: if fnmatch.fnmatch(file_name, "808"): shutil.copy(file_name, ".") FileNotFoundError: [Errno 2] No such file or directory: 'KSHMR_Trap_808_07_F.wav

1 Answers1

0

You have to keep track of the dirpath, then construct the target path of the file with os.join. Keep also in mind that you might need to create sub directories if they do not exist, otherwise you might be trying to overwrite an existing file if the names are the same (which will result in an exception).

import os 
import shutil
import fnmatch

root = '/some/source/path'
target = '/target/path'

for dirpath, dirnames, files in os.walk(root):
    for file_name in files:
        if fnmatch.fnmatch(file_name, "*pattern*"):
            # get the path relative to the source root and create a 
            # new one relative to the target
            path = os.path.join(target, os.path.relpath(dirpath, root))
            if not os.path.exists(path):
                os.makedirs(path)
            shutil.copy(os.path.join(dirpath, file_name), path)
musicamante
  • 41,230
  • 6
  • 33
  • 58