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
CodePudding user response:
I think it should help you:
mkdir destination && find . -regex '.*\(jpg\)' \! -path './destination/*' -exec cp -t destination {}
This command will create a destination directory and copy all files that end in .jpg to the destination folder. Make sure that you stay inside Main_Directory.
CodePudding user response:
Edit:
import shutil
import os
origin_dir = 'dir1/SubDir1' #you can change this for any folder that you want
destination_dir = 'dir1/SubDir2' #you can change this for any folder that you want
files = os.listdir(origin_dir)
for f in files:
#copy only .jpg files
if f.endswith('.jpg'):
shutil.copy(os.path.join(origin_dir, f), destination_dir)