我想知道是否有可能访问linux路径:
/home/dan/CaseSensitivE/test.txt
在某种程度上我们把它写成/home/dan/casesensitive/test.txt
并且它到了正确的位置,意味着python认为路径不区分大小写并允许以这种方式输入它们,尽管它们区分大小写。
答案 0 :(得分:1)
正如克劳斯所说,简单的答案是否定的。但是,您可以采用更费力的路线,并枚举顶级目录中的所有文件夹/文件(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))