|
| 1 | +from os import listdir, rename |
| 2 | +from os.path import isfile, splitext, join, isdir |
| 3 | +from argparse import ArgumentParser |
| 4 | + |
| 5 | +parser = ArgumentParser(description="Batch rename files, stripping a given substring") |
| 6 | + |
| 7 | +parser.add_argument("path", metavar="path", type=str, default="./", nargs="?", help="Path to directory with files to rename. Defaults to current working directory.") |
| 8 | +parser.add_argument("substring", metavar="substring", type=str, help="Substring to strip or replace out of every file in path.") |
| 9 | +parser.add_argument("new_string", metavar="new_string", type=str, default="", nargs="?", help="String to replace for every matching substring.") |
| 10 | +parser.add_argument('-n', action='store_true', help="Rename all files to substring and number them accordingly.") |
| 11 | + |
| 12 | +args = parser.parse_args() |
| 13 | +path = args.path |
| 14 | +substring = args.substring |
| 15 | +numbers = args.n |
| 16 | +new_string = args.new_string |
| 17 | + |
| 18 | +def scanDir(): |
| 19 | + if isdir(path): |
| 20 | + files = [f for f in listdir(path) if isfile(join(path, f))] # Filter out files only |
| 21 | + if len(files) > 0: |
| 22 | + return files # Return what was found |
| 23 | + else: |
| 24 | + print("Directory is empty") |
| 25 | + else: |
| 26 | + print(path, "is not a directory or does not exist.") |
| 27 | + |
| 28 | + |
| 29 | +def renameFiles(files): |
| 30 | + count = 0 |
| 31 | + |
| 32 | + for file in files: |
| 33 | + |
| 34 | + name, ext = splitext(file) |
| 35 | + |
| 36 | + newName = name |
| 37 | + |
| 38 | + if numbers: |
| 39 | + newName = substring + str(count + 1) |
| 40 | + |
| 41 | + elif name.find(substring) != -1: |
| 42 | + newName = name.replace(substring, new_string) |
| 43 | + |
| 44 | + if numbers or name.find(substring) != -1: # if the numbers flag is present or a file can be renamed, then |
| 45 | + count += 1 |
| 46 | + rename("{0}/{1}".format(path, file), "{0}/{1}{2}".format(path, newName, ext)) |
| 47 | + |
| 48 | + |
| 49 | + if count > 0: |
| 50 | + print("Successfully renamed {0} files.".format(count)) |
| 51 | + else: |
| 52 | + print("No files renamed.") |
| 53 | + |
| 54 | +if __name__ == '__main__': |
| 55 | + try: |
| 56 | + files = scanDir() |
| 57 | + if files: |
| 58 | + renameFiles(files) |
| 59 | + |
| 60 | + except Exception as e: |
| 61 | + print(e) |
0 commit comments