-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrename_files.py
More file actions
23 lines (19 loc) · 1.05 KB
/
rename_files.py
File metadata and controls
23 lines (19 loc) · 1.05 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import os
# This function renames all files in the given folder using a consistent naming pattern
def rename_files_in_directory(directory, name_prefix="renamed_file", file_extension=".txt"):
try:
files = os.listdir(directory) # Get all files in the directory
for i, filename in enumerate(files):
new_name = f"{name_prefix}_{i+1}{file_extension}" # Create a new name
old_path = os.path.join(directory, filename) # Full path to the original file
new_path = os.path.join(directory, new_name) # Full path to the new file
os.rename(old_path, new_path) # Rename the file
print(f"Renamed: {filename} -> {new_name}")
except FileNotFoundError:
print("Directory not found. Please check the path.")
except Exception as e:
print(f"An error occurred: {e}")
# Main program block - this runs only when the script is executed directly
if __name__ == "__main__":
folder_path = "/Users/dianyg/python_script" # <-- your folder path
rename_files_in_directory(folder_path)