Skip to content

Instantly share code, notes, and snippets.

@dmitry-mukhin
Created September 9, 2014 13:49
Show Gist options
  • Save dmitry-mukhin/c9445bbd948c8d41338f to your computer and use it in GitHub Desktop.
Save dmitry-mukhin/c9445bbd948c8d41338f to your computer and use it in GitHub Desktop.
filename clean up
import os.path
import string
VALID_CHARS = "_%s%s" % (string.ascii_letters, string.digits)
def clean_filename_part(part):
return ''.join(c for c in part if c in VALID_CHARS)
def clean_filename(fname):
root, ext = os.path.splitext(fname)
root = clean_filename_part(root)
ext = clean_filename_part(ext)
fmt = '{root}.{ext}'
if not ext:
fmt = '{root}'
if not root:
root = 'noroot'
return fmt.format(root=root, ext=ext)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment