Validating a Filename

Generating a filename or getting one from User Input can lead to invalid characters slipping in. Luckily the .Net Framework has a method that returns invalid characters for the current platform which can be used to clean up the filename.

The function (MSDN Docs) returns a list of Chars which need to be converted to strings for use in IronPython. In this example, the characters are just removed from the string.

import System.IO test = r"bad:filename\goesgood?" for c in System.IO.Path.GetInvalidFileNameChars: test = test.replace(c.ToString, '')

print test

Outputs: badfilenamegoesgood

The same as a one-liner: test = ''.join(c for c in test if c not in System.IO.Path.GetInvalidFileNameChars)

Back to Contents.