Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to move images to different directory?

Tags:

python

Very new to Python so please bear with me. I would like to move only the contents of a directory if it exist. Otherwise, would like to move the entire directory. Cleaning up the input directory would be ideal too. Here is what I have so far, for some reason this isn't working:

#!/usr/bin/python

import sys, os, glob, shutil

in_dir = '/images_in/'
out_dir = '/images_out/'
new_dirs = os.listdir(in_dir)
old_dirs = os.listdir(out_dir)

#See if directory already exists. If it doesnt exists, move entire 
directory. If it does exists, move only new images.

for dir in new_dirs:
    if dir not in old_dirs:
        shutil.move(dir, out_dir)
    else:
        new_images = glob.glob(in_dir + dir + '*.jpg')
        for i in new_images:
            shutil.move(i, out_dir + dir + i)
like image 796
Jaken551 Avatar asked May 11 '17 16:05

Jaken551


People also ask

How do I move pictures from one folder to another?

How do I move photos from one folder to another on Android? To move photos from one folder to another on Android, open Gallery app and select the photo you would like to move to another folder. On the bottom menu, tap Add to album and then select the destination folder. Finally, hit Move to confirm.


1 Answers

The problem is that when you do:

for i in new_images:
    shutil.move(i, out_dir + dir + i)

the target path is incorrect. See i is the result of glob.glob on an absolute path. So prepending another absolute path is wrong. You have to use the base name of i instead.

I would do:

for i in new_images:
    shutil.move(i, os.path.join(out_dir, dir, os.path.basename(i)))

Aside:

  • put old_dirs in a set so lookup with in is faster: old_dirs = set(os.listdir(out_dir))
  • use os.path.join instead of string concatenation when handling path parts (as I did in my solution). Ex: new_images = glob.glob(os.path.join(in_dir,dir,'*.jpg')
  • dir is a built-in to list a module contents, that you're shadowing. Not a big concern, but better to avoid it.
like image 119
Jean-François Fabre Avatar answered Oct 26 '22 11:10

Jean-François Fabre