Skip to content

Instantly share code, notes, and snippets.

@sanchitgangwar
Created July 4, 2012 19:40
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 sanchitgangwar/3049199 to your computer and use it in GitHub Desktop.
Save sanchitgangwar/3049199 to your computer and use it in GitHub Desktop.
Move files from multiple directories to one.
#! /usr/local/bin/python3.2
# Moves files from multiple directories to one, and renames them if necessary.
# WHEN IS THIS SCRIPT USEFUL:
# If you have files in multiple directories, say ABC, ABC-1, ABC-2,
# then all the files from the directores will be moved to directory ABC
# and the other directories would be removed.
# If a file with that name already exists, it will be renamed and then moved.
# Renaming: <filename> ==> ABC--<filename>--<some_number>
import os, re, glob, shutil
if __name__ == "__main__":
dirSet = set()
for name in os.listdir('.'):
if(os.path.isdir(name)):
obj = re.search(r'([a-zA-Z]*)(-?[a-zA-Z]+)*', name)
dirSet.update([obj.group()])
dirSet.discard('')
print(dirSet)
rootDir = os.getcwd()
while(dirSet):
curDir = dirSet.pop()
curDirList = glob.glob(curDir + '*')
if curDir in curDirList:
curDirList.remove(curDir)
if(not os.path.isdir(curDir)):
os.mkdir(curDir)
nFiles = len(os.listdir(curDir))
dest = os.path.join(rootDir, curDir)
for direc in curDirList:
os.chdir(direc)
for src in os.listdir('.'):
try:
shutil.move(src, dest)
except:
newSrc = src
while(os.path.exists(os.path.join(dest, newSrc))):
nFiles = nFiles + 1
newSrc = curDir + '--' + src + '--' + str(nFiles)
os.rename(src, newSrc)
shutil.move(newSrc, dest)
os.chdir(rootDir)
os.rmdir(direc)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment