6

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)
Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
Jaken551
  • 161
  • 1
  • 2

1 Answers1

4

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.
Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219