Home > Net >  Iterate through directories, subdirectories, to get files with specialized ext. , copy in new direct
Iterate through directories, subdirectories, to get files with specialized ext. , copy in new direct

Time:03-03

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)

CodePudding user response:

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);

CodePudding user response:

import os
import shutil
import fnmatch

source = "/home/.../test_daten"
ext = '*.trl'
target = "/home/.../test_korpus"

for root, _, files in os.walk(source):
    for filename in fnmatch.filter(files, ext):
        shutil.copy2(os.path.join(root, filename), target)

CodePudding user response:

Maybe your problem is fnmatch.filter(files, extension '.trl'). You have extension from for extension in ext: which will loop though the variable ext and give you a letter from it each time. Your extension '.trl will be ..trl, t.trl, l.trl

import os
import shutil

directory = "/home/.../test_daten"
dest_dir = "/home/.../test_korpus"

for root, _, files in os.walk(directory): #Get the root, files
    for x in files:
        if x.endswith('.trl'): #Check the extension
            shutil.copy2(f'{root}/{x}', dest_dir)
  • Related