Advertisement
iklio

Untitled

Feb 9th, 2019
162
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.23 KB | None | 0 0
  1. #!/usr/bin/python
  2.  
  3. import os, sys, shutil
  4. import errno
  5.  
  6. if len(sys.argv)<4 or ((sys.argv[3] != "dryrun") and (sys.argv[3] != "execute" )):
  7.   print "Usage:\ndirWithTextFiles dirWithShortenedNames mode\nWhere mode is either dryrun or execute, dryrun does not rename dirs\n"
  8.   sys.exit(0)
  9.  
  10. textdir = sys.argv[1]
  11. workingDir = sys.argv[2]
  12. mode = sys.argv[3]
  13. belongsInDir = {}
  14.  
  15. for root, dirs, files in os.walk(textdir):
  16.   for f in files:
  17.     if not f.endswith(".TXT"):
  18.       continue
  19.     #print "File: " + f + "\n"
  20.     fullname = os.path.join(root, f)
  21.     with open(fullname) as listfile:
  22.       for line in listfile:
  23.         #print line
  24.         pathItems = line.split('\\');
  25.         i = 2
  26.         while i < len(pathItems):
  27.           curKey = pathItems[i].lower().strip()
  28.           curValue =  pathItems[i-1].strip()
  29.           if curKey in belongsInDir:
  30.             if belongsInDir[curKey] != curValue:
  31.               belongsInDir[curKey] = " "
  32.               #print "Error: item " + pathItems[i] + " exists in several dirs\n"
  33.           else:
  34.             belongsInDir[curKey] = curValue
  35.             #print "Set " + curKey + " = " + curValue + "\n"
  36.           i += 1
  37.  
  38. for root, dirs, files in os.walk(workingDir, topdown=False):
  39.   for d in dirs:
  40.     if '~' in d:
  41.       #print "Trying to rename " + d + "\n"
  42.       fullname = os.path.join(root, d)
  43.       renameTo = " "
  44.       for f in os.listdir(fullname):
  45.         if f.lower() in belongsInDir and belongsInDir[f.lower()] != " ":
  46.           if renameTo == " ":
  47.             renameTo = belongsInDir[f.lower()]
  48.           else:
  49.             if renameTo != belongsInDir[f.lower()]:
  50.               renameTo = "!"
  51.         else:
  52.           #print "Unable to find " + f + ", " +  belongsInDir.get(f.lower(), "None") + "\n"
  53.           pass
  54.       if renameTo == " ":
  55.         print "Dirname for " + d + " cannot be determined"
  56.       elif renameTo == "!":
  57.         print "Dir contains files from several dirs in the text files"
  58.       else:
  59.         print "Rename " + d + " to " + renameTo
  60.         if mode == "execute":
  61.           oldPath = os.path.join(root, d)
  62.           newPath = os.path.join(root, renameTo)
  63.           os.rename(oldPath, newPath)
  64.           #print "Rename " + oldPath + " to " + newPath
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement