Change file names in bulk with Python

preview_player
Показать описание
How to change file names in folder with Python script?
Ready to use Python script with explanations.

Code:
import os

def rename_files_in_folder(folder_path, prefix='', suffix='', new_name_template=''):
"""
Rename files in the specified folder.

Parameters:
- folder_path: str - path to the folder containing the files to rename.
- prefix: str - prefix to add to each file name.
- suffix: str - suffix to add to each file name.
- new_name_template: str - template for the new name. Use {n} to insert the file number.
If provided, prefix and suffix will be ignored.
"""
print("The specified path is not a valid folder.")
return

for i, file_name in enumerate(files):

if new_name_template:
else:
new_name = f"{prefix}{file_root}{suffix}{file_ext}"

try:
print(f"Renamed '{file_name}' to '{new_name}'")
except Exception as e:
print(f"Failed to rename '{file_name}': {e}")

# Example usage
folder_path = r'C:\Users\Greg\Projekty www\Video\Youtube\made for click\python change names in folder\test files'
rename_files_in_folder(folder_path, prefix='new_', suffix='_backup')
# or use the template
# rename_files_in_folder(folder_path, new_name_template='new_file_{n}')
Рекомендации по теме
welcome to shbcf.ru