Ad
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.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)
Ad
Answer
this is how i usually exclude directories when iterating over os.walk
:
for root, dirs, files in os.walk(drv):
dirs[:] = [d for d in dirs if 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'))
Ad
source: stackoverflow.com
Related Questions
- → What are the pluses/minuses of different ways to configure GPIOs on the Beaglebone Black?
- → Django, code inside <script> tag doesn't work in a template
- → React - Django webpack config with dynamic 'output'
- → GAE Python app - Does URL matter for SEO?
- → Put a Rendered Django Template in Json along with some other items
- → session disappears when request is sent from fetch
- → Python Shopify API output formatted datetime string in django template
- → Can't turn off Javascript using Selenium
- → WebDriver click() vs JavaScript click()
- → Shopify app: adding a new shipping address via webhook
- → Shopify + Python library: how to create new shipping address
- → shopify python api: how do add new assets to published theme?
- → Access 'HTTP_X_SHOPIFY_SHOP_API_CALL_LIMIT' with Python Shopify Module
Ad