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

查看:20
本文介绍了如何删除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 范围内的字符.
    • 目标文件系统不允许的任何其他字符.

    接受的字符列表可能因首次格式化文件系统的机器的操作系统和区域而异.

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

    .NET 有 GetInvalidFileNameCharsGetInvalidPathChars,但我不知道如何从 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天全站免登陆