python输入错误后怎么删除_如何在Python中删除错误的路径字符?

What is the most cross platform way of removing bad path characters (e.g. "\" or ":" on Windows) in Python?

Solution

Because there seems to be no ideal solution I decided to be relatively restrictive and did use the following code:

def remove(value, deletechars):

for c in deletechars:

value = value.replace(c,'')

return value;

print remove(filename, '\/:*?"<>|')

解决方案

Unfortunately, the set of acceptable characters varies by OS and by filesystem.

Use almost any character in the current code page for a name, including Unicode characters and characters in the extended character set (128–255), except for the following:

The following reserved characters are not allowed:

< > : " / \ | ? *

Characters whose integer representations are in the range from zero through 31 are not allowed.

Any other character that the target file system does not allow.

The list of accepted characters can vary depending on the OS and locale of the machine that first formatted the filesystem.

.NET has GetInvalidFileNameChars and GetInvalidPathChars, but I don't know how to call those from Python.

Mac OS: NUL is always excluded, "/" is excluded from POSIX layer, ":" excluded from Apple APIs

HFS+: any sequence of non-excluded characters that is representable by UTF-16 in the Unicode 2.0 spec

HFS: any sequence of non-excluded characters representable in MacRoman (default) or other encodings, depending on the machine that created the filesystem

UFS: same as HFS+

Linux:

native (UNIX-like) filesystems: any byte sequence excluding NUL and "/"

FAT, NTFS, other non-native filesystems: varies

Your best bet is probably to either be overly-conservative on all platforms, or to just try creating the file name and handle errors.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值