Skip to content

Instantly share code, notes, and snippets.

@seanh
Created April 11, 2009 18:30
Show Gist options
  • Select an option

  • Save seanh/93666 to your computer and use it in GitHub Desktop.

Select an option

Save seanh/93666 to your computer and use it in GitHub Desktop.
Turn any string into a valid filename in Python.
def format_filename(s):
"""Take a string and return a valid filename constructed from the string.
Uses a whitelist approach: any characters not present in valid_chars are
removed. Also spaces are replaced with underscores.
Note: this method may produce invalid filenames such as ``, `.` or `..`
When I use this method I prepend a date string like '2009_01_15_19_46_32_'
and append a file extension like '.txt', so I avoid the potential of using
an invalid filename.
"""
valid_chars = "-_.() %s%s" % (string.ascii_letters, string.digits)
filename = ''.join(c for c in s if c in valid_chars)
filename = filename.replace(' ','_') # I don't like spaces in filenames.
return filename
@GwynethLlewelyn
Copy link
Copy Markdown

I get almost all filenames preceded by a dot...

@jowouters
Copy link
Copy Markdown

(just a reminder for others who would like to use this code)
Make sure to import the string module of the standard Python library:

import string

@TomekQ13
Copy link
Copy Markdown

TomekQ13 commented Mar 7, 2021

Works nicely! Thanks!

@drjasonharrison
Copy link
Copy Markdown

Which Open Source License do you share this with?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment