|
| 1 | +import os |
| 2 | + |
| 3 | + |
| 4 | +def rename_files_in_folder(directory: str) -> None: |
| 5 | + """ |
| 6 | + Rename files in the given directory by replacing spaces with underscores. |
| 7 | +
|
| 8 | + Parameters: |
| 9 | + directory (str): The path to the directory containing files to be renamed. |
| 10 | + """ |
| 11 | + try: |
| 12 | + # Verify if the provided directory exists |
| 13 | + if not os.path.isdir(directory): |
| 14 | + raise NotADirectoryError(f"The path '{directory}' is not a valid directory.") |
| 15 | + |
| 16 | + # Loop through each file in the directory |
| 17 | + for filename in os.listdir(directory): |
| 18 | + old_path = os.path.join(directory, filename) |
| 19 | + # Ensure we are working with files only, skip directories |
| 20 | + if os.path.isfile(old_path): |
| 21 | + # Replace spaces in the filename with underscores |
| 22 | + new_filename = filename.replace(" ", "_") |
| 23 | + new_path = os.path.join(directory, new_filename) |
| 24 | + # Rename only if the new filename differs from the old one |
| 25 | + if old_path != new_path: |
| 26 | + os.rename(old_path, new_path) |
| 27 | + print(f"Renamed '{filename}' to '{new_filename}'") |
| 28 | + except Exception as e: |
| 29 | + print(f"An error occurred: {e}") |
| 30 | + |
| 31 | + |
| 32 | +if __name__ == "__main__": |
| 33 | + # You can change the path below to point to your folder |
| 34 | + folder_path: str = './_posts' |
| 35 | + rename_files_in_folder(folder_path) |
0 commit comments