PythonHelfer/RenameFiles.py

50 lines
1.7 KiB
Python

import os
def rename_files_in_directory(directory):
"""
Renames all files in the specified directory based on user input for the base name.
Args:
directory (str): The path to the directory containing the files to rename.
"""
try:
# List all files in the directory
files = [f for f in os.listdir(directory) if os.path.isfile(os.path.join(directory, f))]
if not files:
print("No files found in the directory.")
return
# Ask the user for the base name
base_name = input("Enter the base name for the files (e.g., 'Test'): ")
if not base_name:
print("Base name cannot be empty.")
return
# Sort files alphabetically (optional)
files.sort()
for index, file_name in enumerate(files, start=1):
# Get the file extension
file_extension = os.path.splitext(file_name)[1]
# Construct the new file name
new_name = f"{base_name}{index}{file_extension}"
# Get the full paths
old_path = os.path.join(directory, file_name)
new_path = os.path.join(directory, new_name)
# Rename the file
os.rename(old_path, new_path)
print(f"Renamed: {old_path} -> {new_path}")
print("All files have been renamed successfully.")
except Exception as e:
print(f"An error occurred: {e}")
# Example usage
if __name__ == "__main__":
folder_path = input("Enter the path to the folder: ").strip()
if os.path.isdir(folder_path):
rename_files_in_directory(folder_path)
else:
print("The provided path is not a valid directory.")