Python function makes arbitrary strings valid file names

Is there a built-in function that separates all characters that cannot be in Windows file names from a string or replace them in some way?

eg. function("Some:unicode\symbols")"Some-unicode-symbols"

+3
source share
1 answer
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.

+5
source

All Articles