Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from os import name
- from os import rename
- from os import getcwd
- from os.path import isdir, isfile, exists
- from os.path import dirname, basename
- from os.path import abspath, normcase
- from os.path import join
- from sys import argv
- from glob import glob
- import re
- # Override user match based on items in this tuple,
- # blacklisting certain file and folder names.
- do_not_add_if_file_name_matches = (
- # re.compile(r"^(?i)desktop\.ini$"), # Example
- )
- MAX_NAME = 255
- def scan_list(items, re_pattern):
- for item in items:
- name = basename(item)
- for re_forbidden in do_not_add_if_file_name_matches:
- if re_forbidden.search(name):
- break
- else:
- if re_pattern.search(name):
- yield item
- logo = """____________________________________________
- Regex find and replace in names of files or in names \
- of all files & folders in the specified directories below:
- """
- # Fix for bug where renamed backreferences were lowercased
- if name == "nt":
- normcase = lambda x:x
- if __name__ == "__main__":
- input_paths = [normcase(x) for x in argv[1::]]
- if not input_paths:
- input_paths = ["./"]
- while True:
- # Ensure inputs exist
- input_files, input_directories = [], []
- for input_item in input_paths:
- if isdir(input_item):
- input_directories += [abspath(input_item)]
- elif isfile(input_item):
- input_files += [abspath(input_item)]
- if not input_directories and not input_files:
- print("The inputs no longer exist or cannot be accessed.")
- break
- # Find all affectable files
- all_items = input_files
- for directory in input_directories:
- all_items = [normcase(x) for x in glob(join(directory, "*"))]
- if not all_items:
- print("No input files found.")
- break
- else:
- print("-" * 32)
- print("Regular Expression Find & Replace In File Name:")
- [print("-", x) for x in all_items]
- # User must enter valid regex
- try:
- re_find = re.compile(input("\nRegex Find: "))
- if not re_find.pattern: continue
- except:
- print("Regular expression failed to compile.\n")
- continue
- # Display affected files and folders to user
- matches = list(scan_list(all_items, re_find))
- for item in matches:
- print("-", item)
- print("")
- # User must enter replace/substitute string
- replace = input("%s: " % re_find.pattern) # input("Regex Replace: ")
- # Replace and check for errors
- errors = 0
- for item in matches:
- new_name = re_find.sub(replace, basename(item))
- # Name length sanity
- if not len(new_name):
- print("Skipping - Zero Length Name:", item)
- errors += 1
- continue
- elif len(new_name) > MAX_NAME:
- print("Skipping - Name Over %d Chars:" % MAX_NAME, item)
- errors += 1
- continue
- new_path = join(dirname(item), new_name)
- # Don't overwrite a file
- if exists(new_path):
- print("Skipping - Destination Exists:", item, ">", new_path)
- errors += 1
- continue
- # Attempt to rename and handle exceptions that
- # are possibly related to invalid user input
- try:
- rename(item, new_path)
- except PermissionError as msg:
- print("Skipping - %r" % msg, item)
- print("-", item, ">", new_name)
- print("")
- if errors: input("%d errors occurred. Press ENTER to exit." % errors)
- else:
- print("No existing input folders or files specified.")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement