|Rename files with Windows Explorer|
What if we want to rename files with a specific pattern? Command Prompt comes to rescue. We use
RENcommand to achieve this. With
RENcommand we can rename files with wildcards? and/or *. Let's say we have video files, we want to rename the files that start with "2" and end with ".mkv" into first 2 characters and ends with its extension. The command is:
REN 2*.mkv ??.???
'*' matches any number of characters. So the first parameter means: all files with name starts with '2' and ends with 'mkv'. '?' match a single character. So the second parameters mean first two characters of a filename, followed by '.' (dot), followed by three characters after the dot of the filename.
|Rename files with REN command (1)|
|Rename files with REN command (2)|
|Rename files with Python (1)|
import os, re
path = 'C:/Users/Test/test'
pattern = '^([A-Z]+)\-([0-9]+).*$'
replace = r"\2-\1.mkv"
comp = re.compile(pattern)
for f in os.listdir(path):
full_path = os.path.join(path, f)
match = comp.search(f)
if not match :
new_name = match.expand(replace)
new_name = os.path.join(path, new_name)
print('%s -> %s skipped' % (f, new_name))
pathvariable is, obviously, the absolute path where the files in. The
patternvariable is the regular expression of a filename you want to match. The
replacevariable is the new file name pattern you wish to. You notice that there are \1 and \2 in the replacement pattern. They represent the subgroup match. \1 is the first parenthesized subgroup, the characters that match [A-Z]+ pattern. \2 is the second parenthesized subgroup, the characters that match [0-9]+ pattern.
Here is the result of that Python code:
|Rename files with Python (2)|
regex_rename "<pattern>" "<replacement_pattern>"
regex_rename "^([A-Z]+)\-([0-9]+).*$" "\2-\1.mkv"
Please leave a comment for suggestion or improvement.