Skip to content

Commit 11b1e7f

Browse files
SantanDonSantanDon
authored andcommitted
Modernize batch_file_rename with pathlib and add dry-run feature
1 parent 89f8daa commit 11b1e7f

1 file changed

Lines changed: 45 additions & 47 deletions

File tree

batch_file_rename.py

Lines changed: 45 additions & 47 deletions
Original file line numberDiff line numberDiff line change
@@ -1,57 +1,63 @@
1-
# batch_file_rename.py
2-
# Created: 6th August 2012
3-
4-
"""
5-
This will batch rename a group of files in a given directory,
6-
once you pass the current and new extensions
7-
"""
8-
9-
# just checking
10-
__author__ = "Craig Richards"
11-
__version__ = "1.0"
12-
131
import argparse
142
import os
3+
from pathlib import Path
154

165

17-
def batch_rename(work_dir, old_ext, new_ext):
6+
def batch_rename(work_dir, old_ext, new_ext, dry_run=False):
187
"""
198
This will batch rename a group of files in a given directory,
209
once you pass the current and new extensions
2110
"""
22-
# files = os.listdir(work_dir)
23-
for filename in os.listdir(work_dir):
24-
# Get the file extension
25-
split_file = os.path.splitext(filename)
26-
# Unpack tuple element
27-
root_name, file_ext = split_file
28-
# Start of the logic to check the file extensions, if old_ext = file_ext
29-
if old_ext == file_ext:
30-
# Returns changed name of the file with new extention
31-
newfile = root_name + new_ext
11+
work_path = Path(work_dir)
12+
if not work_path.is_dir():
13+
print(f"Error: {work_dir} is not a valid directory.")
14+
return
15+
16+
print(f"[*] Scanning {work_dir} for files with extension '{old_ext}'...")
17+
18+
found_files = list(work_path.glob(f"*{old_ext}"))
19+
if not found_files:
20+
print(f"[!] No files found with extension '{old_ext}'.")
21+
return
3222

33-
# Write the files
34-
os.rename(os.path.join(work_dir, filename), os.path.join(work_dir, newfile))
35-
print("rename is done!")
36-
print(os.listdir(work_dir))
23+
for file_path in found_files:
24+
new_file_path = file_path.with_suffix(new_ext)
25+
26+
if new_file_path.exists():
27+
print(f"[!] Skip: {new_file_path.name} already exists. Cannot rename {file_path.name}.")
28+
continue
29+
30+
if dry_run:
31+
print(f"[DRY-RUN] Would rename: {file_path.name} -> {new_file_path.name}")
32+
else:
33+
try:
34+
file_path.rename(new_file_path)
35+
print(f"[+] Renamed: {file_path.name} -> {new_file_path.name}")
36+
except Exception as e:
37+
print(f"[!] Error renaming {file_path.name}: {e}")
38+
39+
if not dry_run:
40+
print("[*] Batch rename completed.")
3741

3842

3943
def get_parser():
4044
parser = argparse.ArgumentParser(
41-
description="change extension of files in a working directory"
45+
description="Change extension of files in a working directory"
4246
)
4347
parser.add_argument(
4448
"work_dir",
45-
metavar="WORK_DIR",
46-
type=str,
47-
nargs=1,
48-
help="the directory where to change extension",
49+
help="The directory where to change extension",
50+
)
51+
parser.add_argument(
52+
"old_ext", help="Old extension (e.g., .txt or txt)"
4953
)
5054
parser.add_argument(
51-
"old_ext", metavar="OLD_EXT", type=str, nargs=1, help="old extension"
55+
"new_ext", help="New extension (e.g., .md or md)"
5256
)
5357
parser.add_argument(
54-
"new_ext", metavar="NEW_EXT", type=str, nargs=1, help="new extension"
58+
"--dry-run",
59+
action="store_true",
60+
help="Preview changes without applying them",
5561
)
5662
return parser
5763

@@ -60,22 +66,14 @@ def main():
6066
"""
6167
This will be called if the script is directly invoked.
6268
"""
63-
# adding command line argument
6469
parser = get_parser()
65-
args = vars(parser.parse_args())
70+
args = parser.parse_args()
6671

67-
# Set the variable work_dir with the first argument passed
68-
work_dir = args["work_dir"][0]
69-
# Set the variable old_ext with the second argument passed
70-
old_ext = args["old_ext"][0]
71-
if old_ext and old_ext[0] != ".":
72-
old_ext = "." + old_ext
73-
# Set the variable new_ext with the third argument passed
74-
new_ext = args["new_ext"][0]
75-
if new_ext and new_ext[0] != ".":
76-
new_ext = "." + new_ext
72+
work_dir = args.work_dir
73+
old_ext = args.old_ext if args.old_ext.startswith(".") else "." + args.old_ext
74+
new_ext = args.new_ext if args.new_ext.startswith(".") else "." + args.new_ext
7775

78-
batch_rename(work_dir, old_ext, new_ext)
76+
batch_rename(work_dir, old_ext, new_ext, dry_run=args.dry_run)
7977

8078

8179
if __name__ == "__main__":

0 commit comments

Comments
 (0)