What is the most cross platform way of removing bad path characters (e.g. “\” or “:” on Windows) in Python?
Solution
Because there seems to be no ideal solution I decided to be relatively restrictive and did use the following code:
def remove(value, deletechars):
for c in deletechars:
value = value.replace(c,'')
return value;
print remove(filename, '\/:*?"<>|')
Unfortunately, the set of acceptable characters varies by OS and by filesystem.
Windows:
The list of accepted characters can vary depending on the OS and locale of the machine that first formatted the filesystem.
.NET has GetInvalidFileNameChars and GetInvalidPathChars, but I don’t know how to call those from Python.
Your best bet is probably to either be overly-conservative on all platforms, or to just try creating the file name and handle errors.