Example output
Here’s an optimized Python code snippet that automates file renaming in a directory. The code is structured to be efficient, simple, and easily adaptable. It also includes exception handling, comments for clarity, and best practices such as using context managers and clear variable naming.
```python
import os
def rename_files_in_directory(directory, prefix='', suffix='', new_extension=None):
"""
Renames all files in the specified directory by adding a prefix and/or suffix
to their base names. Optionally, changes file extensions.
Parameters:
directory (str): The path of the directory where files will be renamed.
prefix (str): A prefix to add to the base name of the file. Default is ''.
suffix (str): A suffix to add to the base name of the file. Default is ''.
new_extension (str): If provided, the file extension will be changed to this. Default is None.
"""
try:
# Check if the provided directory exists
if not os.path.isdir(directory):
raise NotADirectoryError(f"The directory '{directory}' does not exist.")
# Iterate through each file in the directory
for filename in os.listdir(directory):
# Construct full file path
file_path = os.path.join(directory, filename)
# Ensure that we are only renaming files, not directories
if os.path.isfile(file_path):
# Extract the base name and extension
base_name, extension = os.path.splitext(filename)
# Build the new file name
new_name = f"{prefix}{base_name}{suffix}{new_extension if new_extension else extension}"
# Generate full new file path
new_file_path = os.path.join(directory, new_name)
# Rename the file
os.rename(file_path, new_file_path)
print(f"Renamed: {filename} -> {new_name}")
except Exception as e:
print(f"Error occurred: {e}")
# Example usage
if __name__ == "__main__":
# Input: Specify the directory path where files should be renamed
target_directory = "/path/to/your/directory" # Change to the path you want to process
# Call the function with desired prefix, suffix, and new extension (optional)
rename_files_in_directory(target_directory, prefix="new_", suffix="_v2", new_extension=".txt")
```
### Key Points in the Code:
1. **Imports**:
- The `os` module is used for file and directory operations.
2. **Function Parameters**:
- `directory`: Path where the files are located.
- `prefix`/`suffix`: Optional additions to the base filename (before and after the original name).
- `new_extension`: Optional, changes the file extension (if not provided, the original extension is kept).
3. **Error Handling**:
- The script checks if the provided path is a directory using `os.path.isdir()`. If not, it raises a `NotADirectoryError`.
- General exceptions are caught and displayed to handle unforeseen errors during file renaming.
4. **File Handling**:
- The script uses `os.listdir()` to retrieve a list of all files in the directory.
- `os.path.isfile()` ensures that only files (not subdirectories) are renamed.
- `os.rename()` performs the renaming operation.
5. **Example Usage**:
- The directory, prefix, suffix, and file extension are customizable via the `rename_files_in_directory()` function. You can change them to adapt the code for different tasks.
6. **Modularity**:
- The function is standalone, so you can easily call it from another script or program.
### Input:
- The user needs to specify the directory path (`target_directory`).
### Output:
- Each renaming operation will be printed, e.g., `"Renamed: old_file.txt -> new_old_file_v2.txt"`.
This code provides a clean and reusable solution for file renaming, with built-in flexibility for future enhancements.