小编Kei*_*ith的帖子

在使用HFS +的OSX上的python中,如何获得现有文件名的正确大小写?

我正在存储有关OSX HFS +文件系统上存在的文件的数据.我后来想迭代存储的数据并确定每个文件是否仍然存在.出于我的目的,我关心文件名区分大小写,所以如果文件名的大小写已经改变,我会认为该文件不再存在.

我开始尝试

os.path.isfile(filename)
Run Code Online (Sandbox Code Playgroud)

但是在HFS +上正常安装OSX时,即使文件名大小写不匹配,也会返回True.我正在寻找一种方法来编写一个isfile()函数,即使文件系统没有,它也会关心大小写.

os.path.normcase()和os.path.realpath()都会在我传入文件的情况下返回文件名.

编辑:

我现在有两个函数似乎适用于限制为ASCII的文件名.我不知道unicode或其他角色会如何影响这个.

第一个是基于omz和Alex L.给出的答案.

def does_file_exist_case_sensitive1a(fname):
    if not os.path.isfile(fname): return False
    path, filename = os.path.split(fname)
    search_path = '.' if path == '' else path
    for name in os.listdir(search_path):
        if name == filename : return True
    return False
Run Code Online (Sandbox Code Playgroud)

第二个可能效率更低.

def does_file_exist_case_sensitive2(fname):
    if not os.path.isfile(fname): return False
    m = re.search('[a-zA-Z][^a-zA-Z]*\Z', fname)
    if m:
        test = string.replace(fname, fname[m.start()], '?', 1)
        print test
        actual = glob.glob(test)
        return len(actual) == 1 and actual[0] == fname
    else:
        return …
Run Code Online (Sandbox Code Playgroud)

python filesystems macos hfs+

7
推荐指数
3
解决办法
750
查看次数

标签 统计

filesystems ×1

hfs+ ×1

macos ×1

python ×1