|
| 1 | +import argparse |
| 2 | +import os |
| 3 | + |
| 4 | +# Rename function |
| 5 | +def rename_files(args): |
| 6 | + # Your file renaming logic here |
| 7 | + print(f"Renaming files in {args.path}...") |
| 8 | + print(f"Prefix: {args.prefix}") |
| 9 | + print(f"Suffix: {args.suffix}") |
| 10 | + print(f"Replace: {args.replace}") |
| 11 | + os.chdir(args.path) |
| 12 | + for file in os.listdir(): |
| 13 | + # Get the file name and extension |
| 14 | + file_name, file_ext = os.path.splitext(file) |
| 15 | + # Add prefix |
| 16 | + if args.prefix: |
| 17 | + file_name = f"{args.prefix}{file_name}" |
| 18 | + # Add suffix |
| 19 | + if args.suffix: |
| 20 | + file_name = f"{file_name}{args.suffix}" |
| 21 | + # Replace substring |
| 22 | + if args.replace: |
| 23 | + file_name = file_name.replace(args.replace[0], args.replace[1]) |
| 24 | + # Rename the file |
| 25 | + print(f"Renaming {file} to {file_name}{file_ext}") |
| 26 | + os.rename(file, f"{file_name}{file_ext}") |
| 27 | + |
| 28 | +# custom type for checking if a path exists |
| 29 | +def path_exists(path): |
| 30 | + if os.path.exists(path): |
| 31 | + return path |
| 32 | + else: |
| 33 | + raise argparse.ArgumentTypeError(f"Path {path} does not exist.") |
| 34 | + |
| 35 | + |
| 36 | +# Set up argument parser |
| 37 | +parser = argparse.ArgumentParser(description='File renaming tool.') |
| 38 | +parser.add_argument('path', type=path_exists, help='Path to the folder containing the files to rename.') |
| 39 | +parser.add_argument('-p', '--prefix', help='Add a prefix to each file name.') |
| 40 | +parser.add_argument('-s', '--suffix', help='Add a suffix to each file name.') |
| 41 | +parser.add_argument('-r', '--replace', nargs=2, help='Replace a substring in each file name. Usage: -r old_string new_string') |
| 42 | + |
| 43 | +args = parser.parse_args() |
| 44 | + |
| 45 | +# Call the renaming function |
| 46 | +rename_files(args) |
0 commit comments