Some people, when confronted with a problem, think âI know, Iâll use regular expressions.â Now they have two problems. â Jamie Zawinski
Think about how many failed attempts you had trying to get the regex right, and even when you got it, it is unreadable line noise.
Here is the right way to rename a file, keeping the path and the file extension unchanged. It is readable and self-explanatory:
import os
filename = 'fee/fi/fo/fum/abc.xyz'
path, name = os.path.split(filename)
name, ext = os.path.splitext(name)
new_filename = os.path.join(path, "bcd" + ext)
And it works regardless of whether you use forward-slashes (Linux, Mac, Unix and Windows) or backslashes (only Windows).
It is a little bit longer to type, but you can see it is correct at a glance. Unlike this regex:
new_filename = re.sub("[^\\\\]+$", 'bcd', filename)
which can only work with backslashes, that is, if it works at all. Who the hell can tell just by reading it??? Not me, thatâs for sure.
If you need to do it a lot of times, put it into a function, and call the function.
Alternatively, you can use pathlib:
import pathlib
filename = pathlib.Path('fee/fi/fo/fum/abc.xyz')
new_filename = filename.with_name('bcd').with_suffix(filename.suffix)