python - Turn a string into a valid filename? -


i have string want use filename, want remove characters wouldn't allowed in filenames, using python.

i'd rather strict otherwise, let's want retain letters, digits, , small set of other characters "_-.() ". what's elegant solution?

the filename needs valid on multiple operating systems (windows, linux , mac os) - it's mp3 file in library song title filename, , shared , backed between 3 machines.

you can @ django framework how create "slug" arbitrary text. slug url- , filename- friendly.

their template/defaultfilters.py (at around line 183) defines function, slugify, that's gold standard kind of thing. essentially, code following.

def slugify(value):     """     normalizes string, converts lowercase, removes non-alpha characters,     , converts spaces hyphens.     """     import unicodedata     value = unicodedata.normalize('nfkd', value).encode('ascii', 'ignore')     value = unicode(re.sub('[^\w\s-]', '', value).strip().lower())     value = unicode(re.sub('[-\s]+', '-', value)) 

there's more, left out, since doesn't address slugification, escaping.


Comments

Popular posts from this blog

windows - Why does Vista not allow creation of shortcuts to "Programs" on a NonAdmin account? Not supposed to install apps from NonAdmin account? -

c++ - How do I get a multi line tooltip in MFC -

unit testing - How to mock PreferenceManager in Android? -