19

如果文件系统不区分大小写,是否有一种简单的方法来检查 Python?我特别考虑像 HFS+ (OSX) 和 NTFS (Windows) 这样的文件系统,即使文件大小写被保留,您也可以在其中访问与 foo、Foo 或 FOO 相同的文件。

4

9 回答 9

19
import os
import tempfile

# By default mkstemp() creates a file with
# a name that begins with 'tmp' (lowercase)
tmphandle, tmppath = tempfile.mkstemp()
if os.path.exists(tmppath.upper()):
    # Case insensitive.
else:
    # Case sensitive.
于 2011-10-23T23:38:38.870 回答
7

Amber 提供的答案会留下临时文件碎片,除非明确处理关闭和删除。为了避免这种情况,我使用:

import os
import tempfile

def is_fs_case_sensitive():
    #
    # Force case with the prefix
    #
    with tempfile.NamedTemporaryFile(prefix='TmP') as tmp_file:
        return(not os.path.exists(tmp_file.name.lower()))

尽管我的用例通常不止一次地对此进行测试,但我将结果存储起来以避免不得不多次接触文件系统。

def is_fs_case_sensitive():
    if not hasattr(is_fs_case_sensitive, 'case_sensitive'):
        with tempfile.NamedTemporaryFile(prefix='TmP') as tmp_file:
            setattr(is_fs_case_sensitive,
                    'case_sensitive',
                    not os.path.exists(tmp_file.name.lower()))
    return(is_fs_case_sensitive.case_sensitive)

如果只调用一次,它会稍微慢一些,而在其他情况下会明显更快。

于 2016-04-12T18:02:58.293 回答
3

关于不同文件系统等的好点,Eric Smith。但是为什么不使用带有 dir 参数的 tempfile.NamedTemporaryFile 并避免自己做所有的上下文管理器呢?

def is_fs_case_sensitive(path):
    #
    # Force case with the prefix
    #
    with tempfile.NamedTemporaryFile(prefix='TmP',dir=path, delete=True) as tmp_file:
        return(not os.path.exists(tmp_file.name.lower()))

我还应该提到,您的解决方案并不能保证您实际上正在测试区分大小写。除非您检查默认前缀(使用 tempfile.gettempprefix())以确保它包含小写字符。所以在这里包括前缀并不是可选的。

您的解决方案会清理临时文件。我同意这似乎很明显,但一个人永远不知道,做一个吗?

于 2016-04-14T02:07:01.630 回答
2

从 Amber 的回答开始,我想出了这段代码。我不确定它是否完全健壮,但它试图解决原始版本中的一些问题(我将在下面提到)。

import os
import sys
import tempfile
import contextlib


def is_case_sensitive(path):
    with temp(path) as tmppath:
        head, tail = os.path.split(tmppath)
        testpath = os.path.join(head, tail.upper())
        return not os.path.exists(testpath)


@contextlib.contextmanager
def temp(path):
    tmphandle, tmppath = tempfile.mkstemp(dir=path)
    os.close(tmphandle)
    try:
        yield tmppath
    finally:
        os.unlink(tmppath)


if __name__ == '__main__':
    path = os.path.abspath(sys.argv[1])
    print(path)
    print('Case sensitive: ' + str(is_case_sensitive(path)))

如果不指定dirin 中的参数mkstemp,区分大小写的问题就很模糊。您正在测试临时目录所在位置的大小写敏感性,但您可能想了解特定路径。

如果您将返回的完整路径转换mkstemp为大写,您可能会错过路径中某处的转换。例如,我在 Linux 上使用 vfat at 安装了一个 USB 闪存驱动器/media/FLASH。测试任何内容的存在/MEDIA/FLASH总是会失败,因为/media它位于(区分大小写的)ext4 分区上,但闪存驱动器本身不区分大小写。挂载的网络共享可能是这样的另一种情况。

最后,也许在 Amber 的回答中不言而喻,您需要清理 mkstemp 创建的临时文件。

于 2016-03-08T18:24:23.043 回答
2

我认为有一个更简单(并且可能更快)的解决方案。以下似乎适用于我测试的地方:

import os.path
home = os.path.expanduser('~')
is_fs_case_insensitive = os.path.exists(home.upper()) and os.path.exists(home.lower())
于 2019-11-13T12:30:51.527 回答
2

@Shrikant 答案的变体,适用于模块中(即不在 REPL 中),即使您的用户没有家:

import os.path
is_fs_case_insensitive = os.path.exists(__file__.upper()) and os.path.exists(__file__.lower())
print(f"{is_fs_case_insensitive=}")

输出(macOS):

is_fs_case_insensitive=True 

还有 Linux 方面:

(ssha)vagrant ~$python3.8 test.py
is_fs_case_insensitive=False 
(ssha)vagrant ~$lsb_release -a
No LSB modules are available.
Distributor ID: Ubuntu
Description:    Ubuntu 20.04 LTS
Release:    20.04
Codename:   focal

FWIW,我通过以下方式检查了pathlib, os,os.path的内容:

[k for k in vars(pathlib).keys() if "case" in k.lower()]

没有任何东西看起来像它,尽管它确实有pathlib.supports_symlinks区分大小写的功能。

以下内容适用于 REPL:

is_fs_case_insensitive = os.path.exists(os.path.__file__.upper()) and os.path.exists(os.path.__file__.lower())
于 2020-06-27T04:57:27.203 回答
1
import os

if os.path.normcase('A') == os.path.normcase('a'):
    # case insensitive
else:
    # case sensitive
于 2013-02-05T13:05:12.450 回答
0

pathlib我认为我们可以在 Python 3.5+ 上一行完成此操作,而无需创建临时文件:

from pathlib import Path

def is_case_insensitive(path) -> bool:
    return Path(str(Path.home()).upper()).exists()

或者反过来:

def is_case_sensitive(path) -> bool:
    return not Path(str(Path.home()).upper()).exists()
于 2021-04-15T00:53:20.000 回答
-1

我相信这是解决这个问题的最简单的方法:

from fnmatch import fnmatch
os_is_case_insensitive = fnmatch('A','a')

来自:https ://docs.python.org/3.4/library/fnmatch.html

如果操作系统不区分大小写,则在执行比较之前,两个参数都将被标准化为全部小写或大写。

于 2018-03-28T21:53:24.103 回答