如何排除中的目录os.步行()?

2024-10-03 21:28:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我要在我的计算机驱动器D到Z中搜索所有vhdx文件,并计算它们的总量。但我想排除目录。如何更改我的代码?你知道吗

extf = ['$RECYCLE.BIN','System Volume Information']
import os
i = 0
az = lambda: (chr(i)+":\\" for i in range(ord("D"), ord("Z") + 1))
for drv in az():
    for root, dirs, files in os.walk(drv):
        for filename in files:
            splitname = filename.split('.')
            if splitname[-1] !="vhdx":
                continue
            file_path = (os.path.join(root, filename))
            print file_path
            i += 1
    if i != 0:
        print ("total vhdx files:",i)

Tags: pathinforifosrootfilesfilename
2条回答

举个例子:

from pathlib import Path
i = 0
az = lambda: (chr(i)+":\\" for i in range(ord("D"), ord("Z") + 1))

for d in az():
    p = Path(d)
    if not p.exists():
        continue
    i += len(list(p.rglob('*.vhdx')))
print("total vhdx files:", i)

这就是我在迭代^{}时通常排除目录的方式:

for root, dirs, files in os.walk(drv):
    dirs[:] = [d for d in dirs if d not in extf]

这里的要点是使用slice-assignmentdirs[:] = ...)来更改dirs(将dirs重新分配给新创建的列表)。你知道吗

如果你想稍微加速,我建议把extf变成set

extf = set(('$RECYCLE.BIN','System Volume Information'))

相关问题 更多 >