The following script should do what you need. It uses os.walk
to recurse through all of your folders looking for files with a .jpg
extension. If a filename already exists in the toDir
, it keeps incrementing a file counter until an empty slot is found and it displays a log of all the copies as it goes:
import os, shutil
srcDir = 'Users/photos/2008/thumbnails/' #files in two more dir deep
toDir = 'Users/external_drive/2008/'
try:
os.makedirs(toDir)
except:
pass
for root, dirs, files in os.walk(srcDir, topdown=True):
for file in files:
src = os.path.join(root, file)
target = os.path.join(toDir, file)
if file.lower().endswith('.jpg'):
index = 1
while os.path.exists(target):
index +=1
target = os.path.join(toDir, os.path.splitext(file)[0]+ "_%d.jpg" % index)
print "Copying: '%s' to '%s'" % (src, target)
shutil.copy(src, target)