os.walk 获取路径,排除目录问题?#dirs[:] = 这种方式不适用

327 天前
 dgzting

1 、环境:目录结构如下,我想排除 D:\目录\目录 1 及其子目录,

    D:\目录
    ├─目录 1 (排除,及其子目录)
    │  ├─目录 1
    │  ├─目录 2
    │  └─目录 3
    ├─目录 2 (保留,及其子目录)
    │  ├─目录 1
    │  ├─目录 2
    │  └─目录 3
    └─目录 3 (保留,及其子目录)
        ├─目录 1
        ├─目录 2
        └─目录 3

生成所有目录路径列表,想通过 if in 排除某些目录

path = r"D:\目录"
allDir = []
exculdeDir=[r"D:\目录\目录 1"]

for root, dirs, files in os.walk(path):
    for i in dirs:
        allDir.append(os.path.join(root, i))

for dirpath in allDir:
    for exculdepath in exculdeDir:
        if exculdepath in dirpath:
            allDir.remove(dirpath)
for i in allDir:
    print(i+" res")

2 、问题: 通过这种方式,排除了 D:\目录\目录 1 ; D:\目录\目录 1\目录 1 ; D:\目录\目录 1\目录 3 ,但是不排除 D:\目录\目录 1\目录 2 ,不知道是什么原因?

835 次点击
所在节点    Python
7 条回复
fuge
327 天前
chatgpt 给的答案,没有经过验证。

问题出在你在循环中修改了 allDir 列表,导致循环遍历时出现了问题。在遍历 allDir 列表的同时,你对其进行了删除操作,导致遍历的元素和列表的索引发生了混乱。

更好的方法是,在遍历 allDir 列表时,创建一个新的列表来保存排除目录后的结果,而不是在原始列表上进行修改。以下是修正后的代码:

python
Copy code
import os

path = r"D:\目录"
allDir = []
exculdeDir = [r"D:\目录\目录 1"]

for root, dirs, files in os.walk(path):
for i in dirs:
allDir.append(os.path.join(root, i))

filteredDir = []

for dirpath in allDir:
exclude = False
for exculdepath in exculdeDir:
if exculdepath in dirpath:
exclude = True
break
if not exclude:
filteredDir.append(dirpath)

for i in filteredDir:
print(i + " res")
这样,你就会得到正确的排除结果。在遍历 allDir 列表时,将不符合排除条件的目录路径添加到 filteredDir 列表中,然后遍历输出 filteredDir 列表,得到正确的排除结果。
NoOneNoBody
327 天前
1.不要在循环中改变循环的目标,问题可能出在这里
2.建议用 os.scandir ,可以一边递归一边排除,不用跑两遍循环
3.如果搜索完再集中处理,有 pandas 模块的话,用 panadas.series.str 相关函数向量化处理更快,当然 allDir 数量少就不必了
deplivesb
327 天前
列表不要一边便利一边删除
nuk
327 天前
for dirpath in allDir[:]:
zhzy
327 天前
glob 了解一下
dgzting
327 天前
感谢各位支持,已解决问题,是遍历中同时删除导致
dgzting
327 天前
@NoOneNoBody 感谢,已解决问题,同时感谢提供一些其他思路

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/964367

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX