Python function to make arbitrary strings valid filenames

穿精又带淫゛_ 提交于 2019-12-22 11:04:10

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!