Created
March 14, 2024 07:39
-
-
Save hoangsonww/cb7424628b2e82fee60eb8b5a60e9a13 to your computer and use it in GitHub Desktop.
Batch File Renamer
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import os | |
| def batch_rename_files(directory, prefix): | |
| """ | |
| Renames all files in the given directory with the given prefix followed by a sequential number, | |
| keeping their original file extensions intact. This can be useful for organizing a large number | |
| of files in a systematic way, such as photos from an event, downloaded files, etc. | |
| Parameters: | |
| - directory: The path to the directory containing the files to be renamed. | |
| - prefix: The prefix to use for renaming the files, which will be followed by an underscore | |
| and a sequential number (e.g., 'photo_001.jpg'). | |
| Example usage: | |
| batch_rename_files("path/to/photos", "holiday") | |
| """ | |
| # Get a list of all files (not directories) in the specified directory | |
| files = [f for f in os.listdir(directory) if os.path.isfile(os.path.join(directory, f))] | |
| # Sort the files to ensure the renaming follows the original alphabetical order | |
| files.sort() | |
| # Loop through each file in the directory | |
| for index, filename in enumerate(files, start=1): | |
| # Generate the new filename using the prefix and a sequential number, preserving the file extension | |
| new_filename = f"{prefix}_{index:03d}{os.path.splitext(filename)[1]}" | |
| # Create full paths for the current (old) and new filenames | |
| old_filepath = os.path.join(directory, filename) | |
| new_filepath = os.path.join(directory, new_filename) | |
| # Rename the file from the old filename to the new filename | |
| os.rename(old_filepath, new_filepath) | |
| # Print a message to indicate the file has been renamed | |
| print(f"Renamed {filename} to {new_filename}") | |
| # Example usage: demonstrates how to use the function | |
| # Note: Before running the script, replace 'path/to/your/directory' with the actual path | |
| # where your files are located, and 'my_prefix' with the desired prefix for the filenames. | |
| if __name__ == "__main__": | |
| directory_path = "path/to/your/directory" # Replace with the actual directory path | |
| file_prefix = "my_prefix" # Replace with your desired prefix | |
| batch_rename_files(directory_path, file_prefix) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment