Recursively move files from a subdirectory to folders in the parent directory

In the following directory

/Drive/Company/images/full_res/

      

there are over 900 .jpg files, for example:

Skywalker.jpg
Pineapple.jpg
Purple.jpg
White.jpg

      

On par with "full_res" ("images"), there are almost as many folders as the images in "full_res", and for the most part they are named accordingly:

..
.
Skywalker/
Pineapple/
Purple/
White/
full_res/

      

I need to move or copy all files in full_res to their named folder in "images" while renaming the file to "export.jpg" at the same time. The result should be like this:

/Drive/Company/images/
----------------------
..
.
Skywalker/export.jpg
Pineapple/export.jpg
Purple/export.jpg
White/export.jpg

      

This is the closest thing . I could find a related question (I think?), But I'm looking for a way to do this using Python. I couldn't create anything here:

import os, shutil

path = os.path.expanduser('~/Drive/Company/images/')
src = os.listdir(os.path.join(path, 'full_res/'))

for filename in src:
    images = [filename.endswith('.jpg') for filename in src]
    for x in images:
        x = x.split('.')
        print x[0] #log to console so I can see it at least doing something (it not)
        dest = os.path.join(path, x[0])
        if not os.path.exists(dest):
            os.makedirs(dest) #create the folder if it doesn't exist
        shutil.copyfile(filename, os.path.join(dest, '/export.jpg'))

      


There are probably many mistakes in this, but I suspect that one of my biggest flaws has something to do with my misunderstanding of the concept of list comprehension. Anyway, I've been struggling with this for so long that I could probably manually move and rename all of these image files. Any help is appreciated.

+3


source to share


1 answer


You are not far from the correct answer:



import os, shutil

path = os.path.expanduser('~/Drive/Company/images/')
src = os.listdir(os.path.join(path, 'full_res'))

for filename in src:
    if filename.endswith('.jpg'):
        basename = os.path.splitext(filename)[0]
        print basename #log to console so I can see it at least doing something (it not)
        dest = os.path.join(path, basename)
        if not os.path.exists(dest):
            os.makedirs(dest) #create the folder if it doesn't exist
        shutil.copyfile(os.path.join(path, 'full_res', filename), os.path.join(dest, 'export.jpg'))

      

+1


source







All Articles