Skip to content

Instantly share code, notes, and snippets.

@cblgh
Last active November 26, 2021 12:03
Show Gist options
  • Save cblgh/c4050a4560953d7f9debeb88bf32e7cf to your computer and use it in GitHub Desktop.
Save cblgh/c4050a4560953d7f9debeb88bf32e7cf to your computer and use it in GitHub Desktop.
general renaming script: change the script's file name to change how it works
#!/usr/bin/env python3
"""
uses the script's name to determine how to rename files in the directory it exists in
e.g. x2y.py -> renames files named with *.x suffixes to now end with *.y suffixes
or more usefully: jpeg2jpg.py -> renames files named with .jpeg suffix to end with .jpg
lowercases the matching suffix (e.g. jpeg2jpg.py will match both JPEG and jpeg)
"""
import sys
import os
scriptname = sys.argv[0]
matching_suffix = scriptname.split("2")[0]
dest_suffix = scriptname.split("2")[1].split(".")[0]
print("matching on *.{}".format(matching_suffix))
print("renaming to *.{}".format(dest_suffix))
fpath = os.getcwd()
counts = 0
with os.scandir(fpath) as it:
for entry in it:
if not entry.name.startswith('.') and entry.is_file():
if entry.name.lower().endswith(matching_suffix):
new_name = "{}.{}".format(entry.name[:-1 * (1+len(matching_suffix))], dest_suffix)
old_fullpath = os.path.join(fpath, entry.name)
new_fullpath = os.path.join(fpath, new_name)
try:
os.rename(old_fullpath, new_fullpath)
counts += 1
except:
print("file {} already existed", new_fullpath)
print("renamed {} files".format(counts))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment