A simple non-recursive directory walker in Python

by

This is taken from here:

A simple directory walker, without the burden of creating a callback for os.path.walk().

This is also usefull for incremental directory walking (where you want to scan remaining directories in subsequent calls).

import os, os.path

startDir = "/"

directories = [startDir]
while len(directories)>0:
    directory = directories.pop()
    for name in os.listdir(directory):
        fullpath = os.path.join(directory,name)
        if os.path.isfile(fullpath):
            print fullpath                # That's a file. Do something with it.
        elif os.path.isdir(fullpath):
            directories.append(fullpath)  # It's a directory, store it.
Advertisements

6 Responses to “A simple non-recursive directory walker in Python”

  1. della Says:

    Why not just using os.walk(), as the comments in the linked page say?

  2. chris Says:

    Because I didn’t have time to read the comments… 😉

  3. aquasana aq-4100 deluxe shower filter Says:

    aquasana aq-4100 deluxe shower filter…

    […]A simple non-recursive directory walker in Python « Look here first![…]…

  4. minecraft games Says:

    Remarkable! Its in fact remarkable piece of writing, I have got much clear idea about
    from this paragraph.

  5. busco mujeres Says:

    It’s really a cool and useful piece of information. I am glad that you simply shared this helpful information with
    us. Please keep us informed like this. Thank you for sharing.

  6. www.facebook.com Says:

    That is a really good tip especially to those fresh to the
    blogosphere. Simple but very precise information… Thank you for sharing this one.
    A must read post!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


%d bloggers like this: