python - 用于 Python 的 Directory Walker

标签 python directory-listing

我目前正在使用来自 Here 的目录 walker

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

这个小改动允许您在文件中拥有完整路径。

任何人都可以帮助我如何使用它来查找文件名吗?我需要完整路径和文件名。

最佳答案

你为什么要自己做这么无聊的事情?

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

输出:

'.'
    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'

但如果你坚持,os.path 中有路径相关的工具, os.basename 就是你正在看的。

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

关于python - 用于 Python 的 Directory Walker,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/775231/

相关文章:

python - 根据另一个数据框中的列名选择数据框中的行

python - Pandas - 按索引 ID 合并两个数据帧

c 编程 - 从 ‘void*’ 到“record_s*”的无效转换

java - 从目录列表下载文件

javascript - 如何制作一个 html 文件来列出其目录中的文件?

c# - 如何在 ASP.NET 中使用 Response.Redirect 从子文件夹到根目录,防止用户查看目录列表

python - 在 Python 中创建快速 RGB 查找表

python - 如何暂停程序直到按下按钮

python - Pytorch: AttributeError: 'function' 对象没有属性 'copy'