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)
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.
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:
old_dirs
in a set
so lookup with in
is faster: old_dirs = set(os.listdir(out_dir))
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.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With