我想知道是否有更快的方法来实现在 python 中返回区分大小写路径的函数。我想出的解决方案之一适用于 linux 和 windows,但需要我迭代 os.listdir,这可能很慢。
此解决方案适用于不需要大量速度的应用程序和上下文:
def correctPath(start, path):
'Returns a unix-type case-sensitive path, works in windows and linux'
start = unicode(start);
path = unicode(path);
b = '';
if path[-1] == '/':
path = path[:-1];
parts = path.split('\\');
d = start;
c = 0;
for p in parts:
listing = os.listdir(d);
_ = None;
for l in listing:
if p.lower() == l.lower():
if p != l:
c += 1;
d = os.path.join(d, l);
_ = os.path.join(b, l);
break;
if not _:
return None;
b = _;
return b, c; #(corrected path, number of corrections)
>>> correctPath('C:\\Windows', 'SYSTEM32\\CmD.EXe')
(u'System32\\cmd.exe', 2)
但是,当上下文从包含 50,000 多个条目的大型数据库中收集文件名时,这不会那么快。
一种方法是为每个目录创建一个字典树。将 dict 树与路径的目录部分匹配,如果发生键丢失,则执行 os.listdir 查找并为新目录创建一个 dict 条目,并删除未使用的部分或保留变量计数器作为一种方式为每个目录分配一个“生命周期”。
最佳答案
以下是您自己的代码的轻微重写,并进行了三处修改:在匹配之前检查文件名是否已经正确,在测试之前将列表处理为小写,使用索引查找相关的“真实案例”文件。
def corrected_path(start, path):
'''Returns a unix-type case-sensitive path, works in windows and linux'''
start = unicode(start)
path = unicode(path)
corrected_path = ''
if path[-1] == '/':
path = path[:-1]
parts = path.split('\\')
cd = start
corrections_count = 0
for p in parts:
if not os.path.exists(os.path.join(cd,p)): # Check it's not correct already
listing = os.listdir(cd)
cip = p.lower()
cilisting = [l.lower() for l in listing]
if cip in cilisting:
l = listing[ cilisting.index(cip) ] # Get our real folder name
cd = os.path.join(cd, l)
corrected_path = os.path.join(corrected_path, l)
corrections_count += 1
else:
return False # Error, this path element isn't found
else:
cd = os.path.join(cd, p)
corrected_path = os.path.join(corrected_path, p)
return corrected_path, corrections_count
我不确定这是否会快得多,尽管进行的测试少了一点,而且开头的“已经正确”的捕获可能会有所帮助。
关于检索区分大小写路径的 Pythonic 方式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14766107/