So I’m using a script to split filenames into “name” and “extension” so I can then apply a bunch of rules to and play around with the “name” and have the script put everything back together at the end.
At the moment, I’m using:
import os, shutil, re
def rename_file (original_filename):
name, extension = os.path.splitext(original_filename)
name = re.sub(r"\'", r"", name) # etc...more of these...
new_filename = name + extension
try:
# moves files or directories (recursively)
shutil.move(original_filename, new_filename)
except shutil.Error:
print ("Couldn't rename file %(original_filename)s!" % locals())
[rename_file(f) for f in os.listdir('.') if not f.startswith('.')]
My problem is that os.path.splitext() includes “the .part(s)” of the “.partX.rar” as part of the filename, whereas I’d like it to be included as part of the file extension.
How can I get the the script to do that (without having a list of “extensions” or a completely separate script for rar files)?
Thanks!
os.path.splitextdoes a reverse search for ‘.’ and returns the first match it finds. So out of the box splitext will not do what you need. If you are just using it to tokenize file names I suggest that you parse the filename yourself by splitting on . taking the left side as the name and then rejoining the right side.Here is one way to do it: