Search code examples
pythonloopssubdirectory

Iterate through directories, subdirectories, to get files with specialized ext. , copy in new directory


I have a question and I went all the other topics through with similar problems but I didn't get my solved.

I have a folder where two subfolders are. Inside of them are a lot of files, but I need just files with extension .trl. I need to copy them and save them in a new folder that is already created. My code don't give me an error but I don't see any result. What I'm doing wrong?

import os
import shutil
import fnmatch

directory = "/home/.../test_daten"
ext = ('.trl')
dest_dir = "/home/.../test_korpus"

for root, dirs, files in os.walk(directory):
    for extension in ext:
        for filename in fnmatch.filter(files, extension+'.trl'):
            source = (os.path.join(root, filename))
            shutil.copy2(source, dest_dir)

Solution

  • Use os.walk() and find all files. Then use endswith() to find the files ending with .trl.

    Sample code:

    import os, shutil;
    
    directory = "/home/.../test_daten";
    dest_dir = "/home/.../test_korpus";
    
    filelist = [];
    
    for root, dirs, files in os.walk(directory):
        for file in files:
            filelist.append(os.path.join(root,file));
    
    for trlFile in filelist:
        if trlFile.endswith(".trl"):
            shutil.copy(trlFile, dest_dir);