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"

4
  • "all characters"? ASCII? Or Unicode? Replaces them "somehow"? Any specific suggestions on what you'd like to see? Commented Mar 9, 2011 at 19:50
  • Thanks for the suggestion, I'll edit it accordingly. Commented Mar 9, 2011 at 19:52
  • Possible answer here? stackoverflow.com/questions/295135/… Commented Mar 9, 2011 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). Commented Mar 9, 2011 at 19:56

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.