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.
"""
if not os.path.isdir(folder_path):
print("The specified path is not a valid folder.")
return
files = os.listdir(folder_path)
files = [f for f in files if os.path.isfile(os.path.join(folder_path, f))]
for i, file_name in enumerate(files):
file_path = os.path.join(folder_path, file_name)
file_root, file_ext = os.path.splitext(file_name)
if new_name_template:
new_name = new_name_template.format(n=i+1) + file_ext
else:
new_name = f"{prefix}{file_root}{suffix}{file_ext}"
new_file_path = os.path.join(folder_path, new_name)
try:
os.rename(file_path, new_file_path)
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}')