-
Notifications
You must be signed in to change notification settings - Fork 1
/
rename.py
executable file
·63 lines (51 loc) · 2.21 KB
/
rename.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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
import os
import argparse
import shutil
import tempfile
def parse_arguments():
parser = argparse.ArgumentParser(description="Copy and rename files with zero padding.")
parser.add_argument('-z', type=int, default=2, help="Zero padding width")
parser.add_argument('src_path', type=str, help="Source directory path")
parser.add_argument('target_pattern', type=str, help="Target pattern with path (e.g., /path/to/destination/Comp_%n.png)")
return parser.parse_args()
def main():
args = parse_arguments()
zero_padding_width = args.z
src_path = args.src_path
target_pattern_with_path = args.target_pattern
if not os.path.isdir(src_path):
print(f"Source directory does not exist: {src_path}")
exit(1)
target_directory = os.path.dirname(target_pattern_with_path)
if not os.path.isdir(target_directory):
print(f"Target directory does not exist: {target_directory}")
exit(1)
target_pattern = os.path.basename(target_pattern_with_path)
tmp_dir = tempfile.mkdtemp()
try:
if os.listdir(src_path):
counter = 0
for filename in os.listdir(src_path):
file_path = os.path.join(src_path, filename)
if os.path.isdir(file_path):
continue
extension = filename.split('.')[-1]
formatted_counter = f"{counter:0{zero_padding_width}d}"
new_file = target_pattern.replace('%n', formatted_counter)
if not new_file.endswith(f".{extension}"):
new_file = f"{new_file}.{extension}"
new_file_path = os.path.join(tmp_dir, new_file)
shutil.copy(file_path, new_file_path)
print(f"Prepared to copy: {file_path} -> {new_file_path}")
counter += 1
for filename in os.listdir(tmp_dir):
shutil.move(os.path.join(tmp_dir, filename), target_directory)
print("All files successfully copied and renamed.")
else:
print("No files found in the source directory.")
except Exception as e:
print(f"An error occurred: {e}")
finally:
shutil.rmtree(tmp_dir)
if __name__ == "__main__":
main()