|
| 1 | +import os |
| 2 | +import argparse |
| 3 | +from typing import Union |
| 4 | + |
| 5 | +def generate_unique_name(directory: str, name: str) -> str: |
| 6 | + """ |
| 7 | + Generate a unique name for a file or folder in the specified directory. |
| 8 | +
|
| 9 | + Parameters: |
| 10 | + ---------- |
| 11 | + directory : str |
| 12 | + The path to the directory. |
| 13 | + name : str |
| 14 | + The name of the file or folder. |
| 15 | +
|
| 16 | + Returns: |
| 17 | + ------- |
| 18 | + str |
| 19 | + The unique name with an index. |
| 20 | + """ |
| 21 | + base_name, extension = os.path.splitext(name) |
| 22 | + index = 1 |
| 23 | + while os.path.exists(os.path.join(directory, f"{base_name}_{index}{extension}")): |
| 24 | + index += 1 |
| 25 | + return f"{base_name}_{index}{extension}" |
| 26 | + |
| 27 | +def rename_files_and_folders(directory: str) -> None: |
| 28 | + """ |
| 29 | + Rename files and folders in the specified directory to lowercase with underscores. |
| 30 | +
|
| 31 | + Parameters: |
| 32 | + ---------- |
| 33 | + directory : str |
| 34 | + The path to the directory containing the files and folders to be renamed. |
| 35 | +
|
| 36 | + Returns: |
| 37 | + ------- |
| 38 | + None |
| 39 | + """ |
| 40 | + if not os.path.isdir(directory): |
| 41 | + raise ValueError("Invalid directory path.") |
| 42 | + |
| 43 | + for name in os.listdir(directory): |
| 44 | + old_path = os.path.join(directory, name) |
| 45 | + new_name = name.lower().replace(" ", "_") |
| 46 | + new_path = os.path.join(directory, new_name) |
| 47 | + |
| 48 | + # Check if the new filename is different from the old filename |
| 49 | + if new_name != name: |
| 50 | + # Check if the new filename already exists in the directory |
| 51 | + if os.path.exists(new_path): |
| 52 | + # If the new filename exists, generate a unique name with an index |
| 53 | + new_path = generate_unique_name(directory, new_name) |
| 54 | + |
| 55 | + os.rename(old_path, new_path) |
| 56 | + |
| 57 | +def main() -> None: |
| 58 | + """ |
| 59 | + Main function to handle command-line arguments and call the renaming function. |
| 60 | +
|
| 61 | + Usage: |
| 62 | + ------ |
| 63 | + python script_name.py <directory_path> |
| 64 | +
|
| 65 | + Example: |
| 66 | + -------- |
| 67 | + python rename_files_script.py /path/to/directory |
| 68 | +
|
| 69 | + """ |
| 70 | + # Create a parser for command-line arguments |
| 71 | + parser = argparse.ArgumentParser(description="Rename files and folders to lowercase with underscores.") |
| 72 | + parser.add_argument("directory", type=str, help="Path to the directory containing the files and folders to be renamed.") |
| 73 | + args = parser.parse_args() |
| 74 | + |
| 75 | + # Call the rename_files_and_folders function with the provided directory path |
| 76 | + rename_files_and_folders(args.directory) |
| 77 | + |
| 78 | +if __name__ == "__main__": |
| 79 | + main() |
0 commit comments