我得到了一个路径列表,我需要在其中检查文件。当然,如果给我一个根目录和一个子目录,就不需要处理子目录了。例如
c:\test // process this
c:\test\pics // do not process this
c:\test2 // process this如何(跨平台)判断一个路径不是另一个路径的子目录。我希望这是跨平台的,只要它们不是周期性的,我就不会担心符号链接(更糟糕的情况是,我最终处理了两次数据)。
更新:这是我最终使用的代码,感谢@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)发布于 2012-01-14 01:18:24
我将维护一组您已经处理过的目录,然后对于每个新路径,在处理之前检查它的父目录是否已经存在于该集中:
import os.path
visited = set()
for path in path_list:
head, tail = os.path.split(path)
while head and tail:
if head in visited:
break
head, tail = os.path.split(head)
else:
process(path)
visited.add(path)请注意,应该对path_list进行排序,以便子目录始终位于其父目录之后。
发布于 2013-08-08 07:51:22
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发布于 2012-01-14 01:23:22
跟踪您已经处理过的目录(以标准化的形式),如果您已经看到它们,就不要再处理它们。像这样的东西应该是有效的:
from os.path import realpath, normcase, sep
dirs = [r"C:\test", r"C:\test\pics", r"C:\test2"]
processed = []
for dir in dirs:
dir = normcase(realpath(dir)) + sep
if not any(dir.startswith(p) for p in processed):
processed.append(dir)
process(dir) # your code herehttps://stackoverflow.com/questions/8854421
复制相似问题