Skip to content Skip to sidebar Skip to footer

How To Exclude Directory In Os.walk()?

I want to search my computer drives D to Z for all vhdx files, and calculate the total amount of them. But I want to exclude directories. How to change my code? extf = ['$RECYCLE.B

Solution 1:

this is how i usually exclude directories when iterating over os.walk:

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

the point here is to use a slice-assignment (dirs[:] = ...) in order to change dirs in-place (reassigning dirs to the newly created list).

if you want to have a slight speedup, i suggest to turn extf into a set:

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

Solution 2:

An example for you:

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

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

Post a Comment for "How To Exclude Directory In Os.walk()?"