Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/python
- import os, sys, shutil
- import errno
- if len(sys.argv)<4 or ((sys.argv[3] != "dryrun") and (sys.argv[3] != "execute" )):
- print "Usage:\ndirWithTextFiles dirWithShortenedNames mode\nWhere mode is either dryrun or execute, dryrun does not rename dirs\n"
- sys.exit(0)
- textdir = sys.argv[1]
- workingDir = sys.argv[2]
- mode = sys.argv[3]
- belongsInDir = {}
- for root, dirs, files in os.walk(textdir):
- for f in files:
- if not f.endswith(".TXT"):
- continue
- #print "File: " + f + "\n"
- fullname = os.path.join(root, f)
- with open(fullname) as listfile:
- for line in listfile:
- #print line
- pathItems = line.split('\\');
- i = 2
- while i < len(pathItems):
- curKey = pathItems[i].lower().strip()
- curValue = pathItems[i-1].strip()
- if curKey in belongsInDir:
- if belongsInDir[curKey] != curValue:
- belongsInDir[curKey] = " "
- #print "Error: item " + pathItems[i] + " exists in several dirs\n"
- else:
- belongsInDir[curKey] = curValue
- #print "Set " + curKey + " = " + curValue + "\n"
- i += 1
- for root, dirs, files in os.walk(workingDir, topdown=False):
- for d in dirs:
- if '~' in d:
- #print "Trying to rename " + d + "\n"
- fullname = os.path.join(root, d)
- renameTo = " "
- for f in os.listdir(fullname):
- if f.lower() in belongsInDir and belongsInDir[f.lower()] != " ":
- if renameTo == " ":
- renameTo = belongsInDir[f.lower()]
- else:
- if renameTo != belongsInDir[f.lower()]:
- renameTo = "!"
- else:
- #print "Unable to find " + f + ", " + belongsInDir.get(f.lower(), "None") + "\n"
- pass
- if renameTo == " ":
- print "Dirname for " + d + " cannot be determined"
- elif renameTo == "!":
- print "Dir contains files from several dirs in the text files"
- else:
- print "Rename " + d + " to " + renameTo
- if mode == "execute":
- oldPath = os.path.join(root, d)
- newPath = os.path.join(root, renameTo)
- os.rename(oldPath, newPath)
- #print "Rename " + oldPath + " to " + newPath
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement