检查Python中文件系统是否区分大小写

19 投票
10 回答
4843 浏览
提问于 2025-04-17 04:52

有没有简单的方法可以在Python中检查一个文件系统是否不区分大小写?我特别想到像HFS+(在Mac上)和NTFS(在Windows上)这样的文件系统,在这些系统中,你可以用foo、Foo或FOO来访问同一个文件,尽管文件的大小写是保留的。

10 个回答

4

你提到的不同文件系统的问题很重要,Eric Smith。不过,为什么不直接用tempfile.NamedTemporaryFile这个方法,并设置dir参数,这样就不用自己处理那些上下文管理器的麻烦了呢?

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()来查看),确保它里面有小写字母。所以在这里加上前缀其实是必须的。

你的方案确实会清理临时文件。我同意这看起来很明显,但谁也不能保证,对吧?

8

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)

如果只调用一次,这样做会稍微慢一点,但在其他情况下会快很多。

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.

当然可以!请把你想要翻译的内容发给我,我会帮你把它变得更简单易懂。

撰写回答