def sanitize_for_filename(text, default=None):
 out = []
 for c in text:
  if (c in valid_filename_chars):
   out.append(c)
  else:
   out.append('_')
 out = ''.join(out)
 if (out in invalid_filenames):
  if (default is None):
   return sanitize_for_filename(str(unique_id()))
  return default
 return out

def sanitize_for_filename ( text , default = None ) : out = [ ] for c in text : if ( c in valid_filename_chars ) : out . append ( c ) else : out . append ( '_' ) out = '' . join ( out ) if ( out in invalid_filenames ) : if ( default is None ) : return sanitize_for_filename ( str ( unique_id ( ) ) ) return default return out
restricts the characters that are allowed in a filename portion; returns default value or a unique id string if result is not a valid name .