首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >访问大小写敏感的路径,而不写入

问访问大小写敏感的路径,而不写入
EN

Stack Overflow用户
提问于 2016-10-06 08:06:11
回答 1查看 58关注 0票数 0

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

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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-10-06 08:40:05

正如克劳斯所说,答案很简单:不。但是,您可以选择一条更艰苦的路线,枚举顶级目录(os.path, glob)中的所有文件夹/文件,将其转换为小写(string.lower),测试相等,逐步下降一级,等等。

这对我来说很管用:

代码语言:javascript
复制
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))
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/39890750

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档