问题
Is there a built-in function which strips all characters which cannot be in Windows filenames from a string or replaces them somehow?
E.g. function("Some:unicode\symbols")
--> "Some-unicode-symbols"
回答1:
import re
arbitrary_string = "File!name?.txt"
cleaned_up_filename = re.sub(r'[/\\:*?"<>|]', '', arbitrary_string)
filepath = os.path.join("/tmp", cleaned_up_filename)
with open(filepath, 'wb') as f:
# ...
Taken from User gx
Obviously adapt to your situation.
来源:https://stackoverflow.com/questions/5251330/python-function-to-make-arbitrary-strings-valid-filenames