Directory Walker for Python

2019-02-07 09:03发布

问题:

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.

回答1:

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



回答2:

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'


回答3:

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

This would also be a lovely place to think recursion.



回答4:

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

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