-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrename-files.py
47 lines (36 loc) · 2.01 KB
/
rename-files.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
import os
import argparse
def rename_files(directory, new_prefix, start_from):
if not os.path.isdir(directory):
print(f"Error: '{directory}' is not a valid directory.")
return
# Retrieve and sort the list of files for consistent renaming order.
files = sorted(os.listdir(directory))
index = start_from
for filename in files:
old_file_path = os.path.join(directory, filename)
# Proceed only if it's a file (skip subdirectories)
if os.path.isfile(old_file_path):
# Preserve the original file extension
_, extension = os.path.splitext(filename)
new_filename = f"{new_prefix}-{index}{extension}"
new_file_path = os.path.join(directory, new_filename)
try:
os.rename(old_file_path, new_file_path)
print(f"Renamed '{filename}' to '{new_filename}'")
except Exception as e:
print(f"Error renaming '{filename}': {e}")
index += 1
if __name__ == '__main__':
# rename_files(
# "/Users/air/Documents/repos/python-rename-files/files/images/original/Balustrades", "balustrades", 2)
rename_files(
"/Users/air/Documents/repos/python-rename-files/files/images/original/Construction", "construction", 10)
# rename_files(
# "/Users/air/Documents/repos/python-rename-files/files/images/test/Trilldoor Burglar", "trilldoor burglar", 1)
# "/Users/air/Documents/repos/python-rename-files/files/images/test/Balustrades"
# "/Users/air/Documents/repos/python-rename-files/files/images/test/Construction"
# "/Users/air/Documents/repos/python-rename-files/files/images/test/Trilldoor Burglar"
# python3 main.py "/Users/air/Documents/repos/python-rename-files/files/images/test/Balustrades", "balustrades", 21
# python3 main.py "/Users/air/Documents/repos/python-rename-files/files/images/test/Construction", "construction", 3
# python3 main.py "/Users/air/Documents/repos/python-rename-files/files/images/test/Trilldoor Burglar", "trilldoor burglar", 1