访问不写大小写的路径

2024-10-17 06:21:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我想知道是否可以访问linux路径,如: /home/dan/CaseSensitivE/test.txt

在某种程度上,我们把它写成/home/dan/casesensitive/test.txt,它放在了正确的位置,这意味着python认为路径不区分大小写,并允许以这种方式输入路径,尽管它们区分大小写。你知道吗


Tags: test路径txthomelinux方式区分dan
1条回答
网友
1楼 · 发布于 2024-10-17 06:21:37

正如克劳斯所说,简单的答案是否定的。然而,你可以采取一种更费力的方法,枚举你的顶级目录(os.path, glob)中的所有文件夹/文件,转换成小写(string.lower),测试相等性,降低一级,等等

这对我很有用:

import os

def match_lowercase_path(path):
    # get absolute path
    path = os.path.abspath(path)

    # try it first
    if os.path.exists(path):
        correct_path = path
    # no luck
    else:
        # works on linux, but there must be a better way
        components = path.split('/')

        # initialise answer
        correct_path = '/'

        # step through
        for c in components:
            if os.path.isdir(correct_path + c):
                correct_path += c +'/'
            elif os.path.isfile(correct_path + c):
                correct_path += c
            else:
                match = find_match(correct_path, c)
                correct_path += match

    return correct_path

def find_match(path, ext):
    for child in os.listdir(path):
        if child.lower() == ext:
            if os.path.isdir(path + child):
                return child + '/'
            else:
                return child
    else:
        raise ValueError('Could not find a match for {}.'.format(path + ext))

相关问题 更多 >