5

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"

Felix Dombek
  • 13,664
  • 17
  • 79
  • 131
  • "all characters"? ASCII? Or Unicode? Replaces them "somehow"? Any specific suggestions on what you'd like to see? – S.Lott Mar 09 '11 at 19:50
  • Thanks for the suggestion, I'll edit it accordingly. – Felix Dombek Mar 09 '11 at 19:52
  • Possible answer here? http://stackoverflow.com/questions/295135/turn-a-string-into-a-valid-filename-in-python – bdk Mar 09 '11 at 19:54
  • Interesting but not an answer, whitelist is impossible for unicode, and blacklist is not portable (although if it won't work otherwise, I'll resort to a blacklist). – Felix Dombek Mar 09 '11 at 19:56

1 Answers1

5
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.

Community
  • 1
  • 1
Elxx
  • 463
  • 1
  • 5
  • 15