Directory Walker for Python
Asked Answered
S

4

5

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:
        try:
            file = self.files[self.index]
            self.index = self.index + 1
        except IndexError:
            # pop next directory from stack
            self.directory = self.stack.pop()
            self.files = os.listdir(self.directory)
            self.index = 0
        else:
            # got a filename
            fullname = os.path.join(self.directory, file)
            if os.path.isdir(fullname) and not os.path.islink(fullname):
                self.stack.append(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.

Selfemployed answered 22/4, 2009 at 0:19 Comment(3)
Can anyone help me how to find just the filename as well using this? I need both the full path, and just the filename.Selfemployed
print os.path.basename(file)Trinee
I would like to say that this isn't properly indented either. everything after class DirectoryWalker needs one indent.Trinee
B
6

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

os.path.normpath

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

os.path.join

Joins two paths

Bedroom answered 22/4, 2009 at 0:19 Comment(1)
Can anyone help me how to find just the filename as well using this? I need both the full path, and just the filename.Selfemployed
G
14

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

Output:

'.'
    d'finction'
    d'.hg'
    -'setup.py'
    -'.hgignore'
'./finction'
    -'finction'
    -'cdg.pyc'
    -'util.pyc'
    -'cdg.py'
    -'util.py'
    -'__init__.pyc'
    -'__init__.py'
'./.hg'
    d'store'
    -'hgrc'
    -'requires'
    -'00changelog.i'
    -'undo.branch'
    -'dirstate'
    -'undo.dirstate'
    -'branch'
'./.hg/store'
    d'data'
    -'undo'
    -'00changelog.i'
    -'00manifest.i'
'./.hg/store/data'
    d'finction'
    -'.hgignore.i'
    -'setup.py.i'
'./.hg/store/data/finction'
    -'util.py.i'
    -'cdg.py.i'
    -'finction.i'
    -'____init____.py.i'

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')
'world.h'
Genisia answered 22/4, 2009 at 0:19 Comment(0)
B
6

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

os.path.normpath

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

os.path.join

Joins two paths

Bedroom answered 22/4, 2009 at 0:19 Comment(1)
Can anyone help me how to find just the filename as well using this? I need both the full path, and just the filename.Selfemployed
F
1

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

This would also be a lovely place to think recursion.

Foresight answered 22/4, 2009 at 0:19 Comment(0)
B
0

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

print os.path.join(os.getcwd(), file)
Brokenhearted answered 22/4, 2009 at 0:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.