Turn a string into a valid filename?



I'd rather be strict than otherwise, so let's say I want to retain only letters, digits, and a small set of other characters like "_-.() ". What's the most elegant solution?


11/28/2016 2:18:47 AM

Accepted Answer

This is the solution I ultimately used:

import unicodedata


def removeDisallowedFilenameChars(filename):



3/30/2009 7:40:17 PM

You can look at the Django framework for how they create a "slug" from arbitrary text. A slug is URL- and filename- friendly.

The Django text utils define a function, slugify(), that's probably the gold standard for this kind of thing. Essentially, their code is the following.

def slugify(value):
    and converts spaces to hyphens.
    import unicodedata
    value = unicode(re.sub('[-\s]+', '-', value))

There's more, but I left it out, since it doesn't address slugification, but escaping.

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow