Loop through directory levels

This is the place for queries that don't fit in any of the other categories.

Loop through directory levels

Postby chops » Mon Sep 02, 2013 11:34 am

I use this code to loop through certain levels of directories and delete included images.
What this code does is to exclude first few levels and work only with the deeper ones (depending on level specified in code).
I would like to achieve INVERTED function. That means i want to WORK WITH first levels and exclude deeper ones.

Code: Select all
import os
from itertools import islice

def drop_n_elements(n,iterable):
   next(islice(iterable, n, n), None)

dir = r'test'

iterable = os.walk(dir)
drop_n_elements(1, iterable)

for root, dirs, files in iterable:
   for name in files:
      if name.endswith(("jpg")):
         os.remove(os.path.join(root, name))
Posts: 1
Joined: Mon Sep 02, 2013 11:26 am

Re: Loop through directory levels

Postby stranac » Mon Sep 02, 2013 3:17 pm

Unfortunately, os.walk() gives you no way of knowing it's current depth.
So you'll need to keep track of that yourself.

Also, you'll want to use the topdown argument as well, to be able to modify which dirs it will recurse to(as explained in the docs).

Something like this should work:
Code: Select all
import os, os.path

def walk_depth(root, max_depth):
    # some initial setup for getting the depth
    root = os.path.normpath(root)
    depth_offset = root.count(os.sep) - 1

    for root, dirs, files in os.walk(root, topdown=True):
        yield root, dirs, files
        # get current depth to determine if we need to stop
        depth = root.count(os.sep) - depth_offset
        if depth >= max_depth:
            # modify dirs so we don't go any deeper
            dirs[:] = []

for root, dirs, files in walk_depth('test', 2):
    # only goes 2 levels down
Friendship is magic!

R.I.P. Tracy M. You will be missed.
User avatar
Posts: 1790
Joined: Thu Feb 07, 2013 3:42 pm

Return to General Coding Help

Who is online

Users browsing this forum: Yahoo [Bot] and 12 guests