我得到了一个路径列表,我需要检查其中的文件。当然,如果给我一个根目录和一个子目录,就不需要处理子目录了。例如
c:\test // process this
c:\test\pics // do not process this
c:\test2 // process this
我如何判断(跨平台)路径不是另一个路径的子目录。最好我希望它是跨平台的,只要符号链接(symbolic link)不是周期性的,我就不担心它们(更糟糕的情况是我最终处理了两次数据)。
更新:这是我最终使用的代码,感谢@F.J
def unique_path_roots(paths):
visited = set()
paths = list(set(paths))
for path in sorted(paths,key=cmp_to_key(locale.strcoll)):
path = normcase(normpath(realpath(path)))
head, tail = os.path.split(path)
while head and tail:
if head in visited:
break
head, tail = os.path.split(head)
else:
yield path
visited.add(path)
最佳答案
def is_subdir(path, directory):
path = os.path.realpath(path)
directory = os.path.realpath(directory)
relative = os.path.relpath(path, directory)
if relative.startswith(os.pardir):
return False
else:
return True
关于python - 如何确定路径是否是另一个路径的子目录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8854421/