我需要加载一个给定名称的文件,但我得到的名称不区分大小写。 “A.txt”实际上可以是“a.txt”。如何快速做到这一点(不是生成所有可能的名称并尝试每个名称)?
您可以列出文件所在的目录(
os.listdir
),并查看是否有与您的文件名匹配的文件。可以通过将两个文件名都小写并进行比较来完成匹配。
如果不获取目录列表并将您要查找的项目和目录中的每个项目与常见案例进行比较,就无法做到这一点。文件系统区分大小写,这就是它的全部内容。
这是我编写的一个函数(好吧,两个)来完全做到这一点,以不敏感的方式递归地匹配文件名:http://portableapps.hg.sourceforge.net/hgweb/portableapps/development-toolkit/file /775197d56e86/utils.py#l78.
def path_insensitive(path):
"""
Get a case-insensitive path for use on a case sensitive system.
>>> path_insensitive('/Home')
'/home'
>>> path_insensitive('/Home/chris')
'/home/chris'
>>> path_insensitive('/HoME/CHris/')
'/home/chris/'
>>> path_insensitive('/home/CHRIS')
'/home/chris'
>>> path_insensitive('/Home/CHRIS/.gtk-bookmarks')
'/home/chris/.gtk-bookmarks'
>>> path_insensitive('/home/chris/.GTK-bookmarks')
'/home/chris/.gtk-bookmarks'
>>> path_insensitive('/HOME/Chris/.GTK-bookmarks')
'/home/chris/.gtk-bookmarks'
>>> path_insensitive("/HOME/Chris/I HOPE this doesn't exist")
"/HOME/Chris/I HOPE this doesn't exist"
"""
return _path_insensitive(path) or path
def _path_insensitive(path):
"""
Recursive part of path_insensitive to do the work.
"""
if path == '' or os.path.exists(path):
return path
base = os.path.basename(path) # may be a directory or a file
dirname = os.path.dirname(path)
suffix = ''
if not base: # dir ends with a slash?
if len(dirname) < len(path):
suffix = path[:len(path) - len(dirname)]
base = os.path.basename(dirname)
dirname = os.path.dirname(dirname)
if not os.path.exists(dirname):
dirname = _path_insensitive(dirname)
if not dirname:
return
# at this point, the directory exists but not the file
try: # we are expecting dirname to be a directory, but it could be a file
files = os.listdir(dirname)
except OSError:
return
baselow = base.lower()
try:
basefinal = next(fl for fl in files if fl.lower() == baselow)
except StopIteration:
return
if basefinal:
return os.path.join(dirname, basefinal) + suffix
else:
return
这是一个简单的递归函数,用于 Eli 上面建议的搜索:
def find_sensitive_path(dir, insensitive_path):
insensitive_path = insensitive_path.strip(os.path.sep)
parts = insensitive_path.split(os.path.sep)
next_name = parts[0]
for name in os.listdir(dir):
if next_name.lower() == name.lower():
improved_path = os.path.join(dir, name)
if len(parts) == 1:
return improved_path
else:
return find_sensitive_path(improved_path, os.path.sep.join(parts[1:]))
return None
制作目录列表;并创建一个字典,其中包含大写文件名到实际大小写文件名的映射。然后,将输入的内容设为大写,然后在字典中查找。
pathlib
glob()
在 Python 3.12 中获得了 case_sensitive=False
参数。
注意:默认为
None
,表示平台特定的大小写规则。
https://docs.python.org/3/library/pathlib.html#pathlib.Path.glob