Skip to content

Instantly share code, notes, and snippets.

@rldotai
Created September 14, 2021 16:02
Show Gist options
  • Save rldotai/cc1e4169e9ec6941a9b332f52217c6df to your computer and use it in GitHub Desktop.
Save rldotai/cc1e4169e9ec6941a9b332f52217c6df to your computer and use it in GitHub Desktop.
Bulk renaming files with Python to make them more consistent/easier to type. Not especially difficult, but it comes up surprisingly often.
"""
Renaming files to make them more consistent/easier to type.
"""
import unicodedata
import re
from pathlib import Path
# You can use whatever function you prefer, but Django's slugify is pretty slick
def slugify(value, allow_unicode=False):
"""
Taken from https://github.com/django/django/blob/master/django/utils/text.py
Convert to ASCII if 'allow_unicode' is False. Convert spaces or repeated
dashes to single dashes. Remove characters that aren't alphanumerics,
underscores, or hyphens. Convert to lowercase. Also strip leading and
trailing whitespace, dashes, and underscores.
"""
value = str(value)
if allow_unicode:
value = unicodedata.normalize("NFKC", value)
else:
value = (
unicodedata.normalize("NFKD", value)
.encode("ascii", "ignore")
.decode("ascii")
)
value = re.sub(r"[^\w\s-]", "", value.lower())
return re.sub(r"[-\s]+", "_", value).strip("-_")
# Get all files contained within a directory and its subdirectories
to_rename = (x for x in SOME_DIRECTORY.rglob("**/*") if x.is_file())
# Rename all paths accordingly
for path in to_rename:
new_path = path.with_stem(slugify(path.stem))
print(path)
print(new_path)
path.rename(new_path)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment