Generate safe filenames using Python

This function removes illegal  characters to create file names that are safe to use on most operating systems.

import string

## Make a file name that only contains safe charaters
# @param inputFilename A filename containing illegal characters
# @return A filename containing only safe characters
def makeSafeFilename(inputFilename):   
     safechars = string.letters + string.digits + " -_."
    return filter(lambda c: c in safechars, inputFilename)
     return ""  

print makeSafeFilename("test1******.txt")  # test1.txt

print makeSafeFilename("test2:\.txt") # test2.txt

print makeSafeFilename("test39328764876!%^&*().txt") # test39328764876.txt
This entry was posted in Python.

Leave a Reply

Your email address will not be published. Required fields are marked *