Skip to content

Instantly share code, notes, and snippets.

@positlabs
Created May 22, 2013 22:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save positlabs/5631317 to your computer and use it in GitHub Desktop.
Save positlabs/5631317 to your computer and use it in GitHub Desktop.
utility for batch operations on files
import os
import shutil
def renameByType(type, toType, dir):
for root, dirs, files in os.walk(dir):
for f in files:
filename, filetype = os.path.splitext(f)
if(f.find(type) != -1):
print os.path.join(root, f), " -> ", f.replace(type, toType)
shutil.move(os.path.join(root, f), os.path.join(root, f.replace(type, toType)))
def deleteFileByType(type, dir):
deleted = os.path.join(dir, "deleted")
if(os.path.exists(deleted) == False):
os.mkdir(deleted)
for root, dirs, files in os.walk(dir):
for f in files:
if(f.find(type) != -1):
print os.path.join(root, f)
shutil.move(os.path.join(root, f), os.path.join(os.path.join(dir, "deleted"), f))
# sorts files into a folder if the filename matches an existing file
def moveByMatched(src, dst):
dstPaths = []
dstFileNames = []
overwriteAll = False
for root, dirs, files in os.walk(dst):
for f in files:
filename, filetype = os.path.splitext(f)
if(len(filename) > 0):
dstFileNames.append(filename)
dstPaths.append(root)
for srcRoot, srcDirs, srcFiles in os.walk(src):
for f in srcFiles:
filename = os.path.splitext(f)[0]
try:
index = dstFileNames.index(filename)
moveTo = os.path.join(dstPaths[index], f)
# prompt overwrite existing, or overwrite all
if(os.path.exists(moveTo) and overwriteAll == False):
answer = raw_input("overwrite existing file? (y, n, all) \n-> " + moveTo)
if(answer == "all"):
overwriteAll = True
if(answer == "y" or overwriteAll == True):
print os.path.join(srcRoot, f), " -> ", dstPaths[index]
shutil.move(os.path.join(srcRoot, f), moveTo)
else:
print os.path.join(srcRoot, f), " -> ", dstPaths[index]
shutil.move(os.path.join(srcRoot, f), moveTo)
except ValueError:
pass
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment