使用 os.walk 在过滤器中导航特定目录
Navigating specific dirs in filter with os.walk
我知道我可以使用类似
的方法从 os.walk 中删除目录
for root, dirs, files in os.walk('/path/to/dir'):
ignore = ['dir1', 'dir2']
dirs[:] = [d for d in dirs if d not in ignore]
我想做相反的事情,所以只保留列表中的目录。我尝试了一些变体,但无济于事。任何指针将不胜感激。
我感兴趣的目录低于 2 个级别,因此我接受了评论并为子级别创建了全局变量,并使用了以下代码。
预期功能
for root, dirs, files in os.walk(global_subdir):
keep = ['dir1', 'dir2']
dirs[:] = [d for d in dirs if d in keep]
for filename in files:
print os.path.join(root, filename)
如已删除答案的评论中所述 -
As mentioned already, this doesnt work. The dirs in keep are 2 levels sub root. Im guessing this is causing the problem
问题是您所需目录的上一级目录不会被遍历,因为它不在您的 keep
列表中,因此程序永远不会到达您所需的目录。
解决此问题的最佳方法是从 os.walk
所需目录的上一级目录开始。
但如果这是不可能的(比如在遍历之前可能不知道所需目录的上一级目录)或(所需目录在上一级有不同的目录)。而您真正想要的是避免循环遍历不在 keep
目录中的目录的文件。
一个解决方案是遍历所有目录,但仅当 root
在 keep
列表中时才循环遍历 files
(或为了更好的性能而设置)。示例 -
keep = set(['required directory1','required directory2'])
for root, dirs, files in os.walk(global_subdir):
if root in keep:
for filename in files:
print os.path.join(root, filename)
我知道我可以使用类似
的方法从 os.walk 中删除目录for root, dirs, files in os.walk('/path/to/dir'):
ignore = ['dir1', 'dir2']
dirs[:] = [d for d in dirs if d not in ignore]
我想做相反的事情,所以只保留列表中的目录。我尝试了一些变体,但无济于事。任何指针将不胜感激。
我感兴趣的目录低于 2 个级别,因此我接受了评论并为子级别创建了全局变量,并使用了以下代码。
预期功能
for root, dirs, files in os.walk(global_subdir):
keep = ['dir1', 'dir2']
dirs[:] = [d for d in dirs if d in keep]
for filename in files:
print os.path.join(root, filename)
如已删除答案的评论中所述 -
As mentioned already, this doesnt work. The dirs in keep are 2 levels sub root. Im guessing this is causing the problem
问题是您所需目录的上一级目录不会被遍历,因为它不在您的 keep
列表中,因此程序永远不会到达您所需的目录。
解决此问题的最佳方法是从 os.walk
所需目录的上一级目录开始。
但如果这是不可能的(比如在遍历之前可能不知道所需目录的上一级目录)或(所需目录在上一级有不同的目录)。而您真正想要的是避免循环遍历不在 keep
目录中的目录的文件。
一个解决方案是遍历所有目录,但仅当 root
在 keep
列表中时才循环遍历 files
(或为了更好的性能而设置)。示例 -
keep = set(['required directory1','required directory2'])
for root, dirs, files in os.walk(global_subdir):
if root in keep:
for filename in files:
print os.path.join(root, filename)