Advertisement
Vearie

Regre

Nov 23rd, 2018
200
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 3.31 KB | None | 0 0
  1. from os import name
  2. from os import rename
  3. from os import getcwd
  4. from os.path import isdir, isfile, exists
  5. from os.path import dirname, basename
  6. from os.path import abspath, normcase
  7. from os.path import join
  8.  
  9. from sys import argv
  10. from glob import glob
  11. import re
  12.  
  13. # Override user match based on items in this tuple,
  14. # blacklisting certain file and folder names.
  15. do_not_add_if_file_name_matches = (
  16.     # re.compile(r"^(?i)desktop\.ini$"), # Example
  17. )
  18.  
  19. MAX_NAME = 255
  20.  
  21. def scan_list(items, re_pattern):
  22.     for item in items:
  23.         name = basename(item)
  24.         for re_forbidden in do_not_add_if_file_name_matches:
  25.             if re_forbidden.search(name):
  26.                 break
  27.         else:
  28.             if re_pattern.search(name):
  29.                 yield item
  30.  
  31. logo = """____________________________________________
  32. Regex find and replace in names of files or in names \
  33. of all files & folders in the specified directories below:
  34. """
  35.  
  36. # Fix for bug where renamed backreferences were lowercased
  37. if name == "nt":
  38.     normcase = lambda x:x
  39.  
  40. if __name__ == "__main__":
  41.     input_paths = [normcase(x) for x in argv[1::]]
  42.     if not input_paths:
  43.         input_paths = ["./"]
  44.    
  45.     while True:
  46.         # Ensure inputs exist
  47.         input_files, input_directories = [], []
  48.        
  49.         for input_item in input_paths:
  50.             if isdir(input_item):
  51.                 input_directories += [abspath(input_item)]
  52.            
  53.             elif isfile(input_item):
  54.                 input_files += [abspath(input_item)]
  55.        
  56.         if not input_directories and not input_files:
  57.             print("The inputs no longer exist or cannot be accessed.")
  58.             break
  59.        
  60.         # Find all affectable files
  61.         all_items = input_files
  62.         for directory in input_directories:
  63.             all_items = [normcase(x) for x in glob(join(directory, "*"))]
  64.        
  65.         if not all_items:
  66.             print("No input files found.")
  67.             break
  68.         else:
  69.             print("-" * 32)
  70.             print("Regular Expression Find & Replace In File Name:")
  71.             [print("-", x) for x in all_items]
  72.        
  73.         # User must enter valid regex
  74.         try:
  75.             re_find = re.compile(input("\nRegex Find: "))
  76.             if not re_find.pattern: continue
  77.         except:
  78.             print("Regular expression failed to compile.\n")
  79.             continue
  80.        
  81.         # Display affected files and folders to user
  82.         matches = list(scan_list(all_items, re_find))
  83.         for item in matches:
  84.             print("-", item)
  85.         print("")
  86.        
  87.         # User must enter replace/substitute string
  88.         replace = input("%s: " % re_find.pattern) # input("Regex Replace: ")
  89.        
  90.         # Replace and check for errors
  91.         errors = 0
  92.         for item in matches:
  93.             new_name = re_find.sub(replace, basename(item))
  94.            
  95.             # Name length sanity
  96.             if not len(new_name):
  97.                 print("Skipping - Zero Length Name:", item)
  98.                 errors += 1
  99.                 continue
  100.             elif len(new_name) > MAX_NAME:
  101.                 print("Skipping - Name Over %d Chars:" % MAX_NAME, item)
  102.                 errors += 1
  103.                 continue
  104.            
  105.             new_path = join(dirname(item), new_name)
  106.            
  107.             # Don't overwrite a file
  108.             if exists(new_path):
  109.                 print("Skipping - Destination Exists:", item, ">", new_path)
  110.                 errors += 1
  111.                 continue
  112.            
  113.             # Attempt to rename and handle exceptions that
  114.             # are possibly related to invalid user input
  115.             try:
  116.                 rename(item, new_path)
  117.             except PermissionError as msg:
  118.                 print("Skipping - %r" % msg, item)
  119.             print("-", item, ">", new_name)
  120.        
  121.         print("")
  122.         if errors: input("%d errors occurred. Press ENTER to exit." % errors)
  123.     else:
  124.         print("No existing input folders or files specified.")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement