Title: [Python] Filename sanitizer snippet 1 Author: waterapple Pastebin link: http://pastebin.com/PGA4jA8w First Edit: Thursday 23rd of August 2012 07:04:10 PM CDT Last Edit: Thursday 23rd of August 2012 07:04:10 PM CDT def sanitizefilename(unsanitizedfn,debug=False):         #make safe for a filename         if debug:                 print unsanitizedfn         #remove disallowed characters         filenamesubbed = re.sub('[^A-Za-z0-9 \.]+', '-', unsanitizedfn)         if debug:                 print filenamesubbed         #remove duplicate underscores and spaces         filenamesubbed = re.sub("_+", "_", filenamesubbed)         if debug:                 print filenamesubbed         #make sure first and last char arent spacees         filenametrim = filenamesubbed         while True:                 if debug:                         print filenametrim                 #remove last char if its a space                 if filenametrim[-1] == ' ':                         filenametrim = filenametrim[:-1]                 #remove first char if its a space                 if filenametrim[0] == ' ':                         filenametrim = filenametrim[1:]                 #if first and last chars arent spaces, continue                 if filenametrim[0] != ' ' and filenametrim[-1] != ' ':                         fnout = filenametrim                 c += 1#increment counter                 if c >= 100:#if we fucked up, ignote trimming                         fnout = filenamesubbed         return fnout