如何在Python中删除错误的路径字符? [英] How to remove bad path characters in Python?

查看:136
本文介绍了如何在Python中删除错误的路径字符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Python中删除错误路径字符(例如Windows上的"\"或:")的最跨平台方法是什么?

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

因为似乎没有理想的解决方案,所以我决定采用相对限制性的方法,并确实使用了以下代码:

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.

  • 使用当前代码页中的几乎所有字符作为名称,包括Unicode字符和扩展字符集(128–255)中的字符,但以下各项除外:
    • 不允许使用以下保留字符:
      < > :"/\ |?*
    • 不允许使用整数表示形式从0到31的字符.
    • 目标文件系统不允许的其他任何字符.
  • 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具有 GetInvalidFileNameChars 和<一个href ="http://msdn.microsoft.com/zh-cn/library/system.io.path.getinvalidpathchars.aspx" rel ="noreferrer"> GetInvalidPathChars ,但我不知道该怎么做从Python调用它们.

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

  • HFS +:在Unicode 2.0规范中可由UTF-16表示的任何非排除字符序列
  • HFS:可以用MacRoman(默认)或其他编码表示的任何非排除字符序列,具体取决于创建文件系统的机器
  • UFS:与HFS +
  • 相同
  • 本地(类似于UNIX)文件系统:不包括NUL和"/"的任何字节序列
  • FAT,NTFS,其他非本地文件系统:各不相同

您最好的选择可能是在所有平台上都过于保守,或者只是尝试创建文件名并处理错误.

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

这篇关于如何在Python中删除错误的路径字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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