Directory Walker for Python

I am currently using the directory walker from Here

import os
class DirectoryWalker:
# a forward iterator that traverses a directory tree

def __init__(self, directory):
    self.stack = [directory]
    self.files = []
    self.index = 0

def __getitem__(self, index):
    while 1:
            file = self.files[self.index]
            self.index = self.index + 1
        except IndexError:
            # pop next directory from stack
   = self.stack.pop()
            self.files = os.listdir(
            self.index = 0
            # got a filename
            fullname = os.path.join(, file)
            if os.path.isdir(fullname) and not os.path.islink(fullname):
            return fullname

for file in DirectoryWalker(os.path.abspath('.')):
    print file

This minor change allows you to have the full path within the file.

Can anyone help me how to find just the filename as well using this? I need both the full path, and just the filename.

Asked by: Abigail569 | Posted: 06-12-2021

Answer 1

Why do you want to do such boring thing yourself?

for path, directories, files in os.walk('.'):
    print 'ls %r' % path
    for directory in directories:
        print '    d%r' % directory
    for filename in files:
        print '    -%r' % filename



But if you insist, there's path related tools in os.path, os.basename is what you are looking at.

>>> import os.path
>>> os.path.basename('/hello/world.h')

Answered by: Cherry944 | Posted: 07-01-2022

Answer 2

Rather than using '.' as your directory, refer to its absolute path:

for file in DirectoryWalker(os.path.abspath('.')):
    print file

Also, I'd recommend using a word other than 'file', because it means something in the python language. Not a keyword, though so it still runs.

As an aside, when dealing with filenames, I find the os.path module to be incredibly useful - I'd recommend having a look through that, especially


Normalises paths (gets rid of redundant '.'s and 'theFolderYouWereJustIn/../'s)


Joins two paths

Answered by: Edgar256 | Posted: 07-01-2022

Answer 3

os.path.dirname()? os.path.normpath()? os.path.abspath()?

This would also be a lovely place to think recursion.

Answered by: Darcy841 | Posted: 07-01-2022

Answer 4

Just prepend the current directory path to the "./foo" path returned:

print os.path.join(os.getcwd(), file)

Answered by: Patrick705 | Posted: 07-01-2022

Similar questions

active directory - How to Retrieve name of current Windows User (AD or local) using Python?

How can I retrieve the name of the currently logged in user, using a python script? The function should work regardless of whether it is a domain/ad user or a local user.

ftp - Using Python's ftplib to get a directory listing, portably

You can use ftplib for full FTP support in Python. However the preferred way of getting a directory listing is: # File: import ftplib ftp = ftplib.FTP("") ftp.login("anonymous", "ftplib-example-1") data = [] ftp.dir(data.append) ftp.quit() for line in data: print "-", line Which yields: $ python - total 34 - dr...

How do I change directory back to my original working directory with Python?

I have a function that resembles the one below. I'm not sure how to use the os module to get back to my original working directory at the conclusion of the jar's execution. def run(): owd = os.getcwd() #first change dir to build_dir path os.chdir(testDir) #run jar from test directory os.system(cmd) #change dir back to original working directory (owd) note: I think...

python - How to check if a file can be created inside given directory on MS XP/Vista?

I have a code that creates file(s) in user-specified directory. User can point to a directory in which he can't create files, but he can rename it. I have created directory for test purposes, let's call it C:\foo. I have following permissions to C:\foo: Traversing directory/Execute file Removing subfolders and files Removing Read permi...

java - Mixed language source directory layout

We are running a large project with several different languages: Java, Python, PHP, SQL and Perl. Until now people have been working in their own private repositories, but now we want to merge the entire project in a single repository. The question now is: how should the directory structure look? Should we have separate directories for each language, or should we separate it by component/project? How well does pyt...

import - Current working directory no longer inherited from calling process from python 2.5 onwards?

I updated my python version on windows 2003 server from 2.4 to 2.5. In 2.4 I could import a file "" from a subdirectory c:\application\subdir\ like this: import sub1 as long as the calling script that lives in c:\application was started like this: c:\application\subdir>python ..\ But in 2.5 it no longer works for me:

How do I tell a file from directory in Python?

When using os.listdir method I need to tell which item in the resulting list is a directory or just a file. I've faced a problem when I had to go through all the directories in this list, and then add a file in every single directory. Is there a way to go through this list and remove all files from it? If it isn't possible to do with os.listdir, what method should I use instead? Thanks.

python - Using paver and nose together with an atypical directory structure

I'm trying to write a task for Paver that will run nosetests on my files. My directory structure looks like this: project/ build/ subproject/ test/ Doctests (using the --with_doctest option) should be run on all the *.py files, while onl...

file - Directory checksum with python?

So I'm in the middle of web-based filesystem abstraction layer development. Just like file browser, except it has some extra features like freaky permissions etc. I would like users to be notified somehow about directory changes. So, i.e. when someone uploads a new file via FTP, certain users should get a proper message. It is not required for the message to be extra detailed, I don't really need to show the exa...

windows - Changing prompt working directory via Python script

Is it possible to change the Windows command prompt working directory via Python script? e.g. >> cd >> c:\windows\system32 >> >> cd >> c:\windows I have tried a few things which don't work: import os os.chdir(path) import os, subprocess subprocess.Popen("chdir /D \"%s\"" %path,...

Still can't find your answer? Check out these communities...

PySlackers | Full Stack Python | NHS Python | Pythonist Cafe | Hacker Earth | Discord Python