Python函数使任意字符串成为有效的文件名 [英] Python function to make arbitrary strings valid filenames

查看:348
本文介绍了Python函数使任意字符串成为有效的文件名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有内置功能可以从字符串中删除Windows文件名中不能出现的所有字符或以某种方式替换它们?

Is there a built-in function which strips all characters which cannot be in Windows filenames from a string or replaces them somehow?

例如function("Some:unicode\symbols")-> "Some-unicode-symbols"

推荐答案

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:
    # ...

来自用户 gx
显然可以适应您的情况.

Taken from User gx
Obviously adapt to your situation.

这篇关于Python函数使任意字符串成为有效的文件名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆