Search code examples
pythonlinuxshellcopycopy-paste

Copy files from specific subfolders


I am trying to copy files from specific subfolder into a new folder but nothing working for me. The file structure look like:

Main_Directory
     SubDirectory1
        targetfolder
           file1.gz
           file1.jpg
        unwantedfolder
           file1.gz
           file1.jpg
     SubDirectory2
        targetfolder
           file2.gz
           file2.jpg
        unwantedfolder
           file2.gz
           file2.jpg
     SubDirectory3
        targetfolder
           file3.gz
           file3.jpg
        unwantedfolder
           file1.gz
           file1.jpg

I am trying to copy all the jpg files from the target folder to new folder. I tried cp and find function but could not get the output.

`find -name "*/targetfolder/..qz" | xargs cp --parents -t /depot/only_pics/

Also tried

`

import os
from os.path import join, isfile

BASE_PATH = '/Main_Directory/'
SUBFOLDER = 'targetfolder'

for folder, subfolders, *_ in os.walk(BASE_PATH):
    if SUBFOLDER in subfolders:
        full_path = join(BASE_PATH, folder, SUBFOLDER)
        files = [f for f in os.listdir(full_path) if isfile(join(full_path, f)) and f.lower().endswith(('.jpg', '.jpg'))]
        for f in files:
            file_path = join(full_path, f)
            print (f'Copy {f} /depot/only_pics/')

Can you please direct me to the solution? I just want to copy from each subfolder


Solution

  • I think it should help you:

    mkdir destination && find . -regex '.*\(jpg\)' \! -path './destination/*' -not -path '*/unwantedfolder/*' -exec cp -t destination {} +
    

    This command will create a destination directory and copy all files that end in .jpg, ignoring files in unwantedfolder folder, to the destination folder. Make sure that you stay inside Main_Directory.