首页 > 解决方案 > 递归地跟随目录树

问题描述

所以我正在使用 Python 并且仍然很新,我需要能够遍历目录中的所有文件夹,所以如果/foo包含/foo/bar并且/foo/bar/foo我想列出所有条目。到目前为止,我已经创建了一个在它自己的文件中工作的类,但是当我尝试import它时,我得到一个错误说明TypeError: coercing to Unicode: need string or buffer, builtin_function_or_method found

在文件中找到函数,DirTree所以我通过以下方式导入它:

from DirTree import DirTrav

DirList = DirTrav(dir).returnList()

代码可以在下面找到。

import os

class DirTrav:
    DList = []
    dir = ""

    def __init__(self, dirTrav):
        self.dir = dirTrav

    def dirTree(self, start):
        _subFolders = os.listdir(start)
        for f in _subFolders:
            _newFolder = os.path.join(start, f)
            if os.path.isdir( _newFolder):
                self.DList.append(_newFolder)
                self.dirTree(_newFolder)

    def returnList(self):
        self.dirTree(dir)
        return self.DList

标签: python

解决方案


使用os.walk()

for root, dirs, files in os.walk():
    for filename in files:
        # do something with filename (files and will return all files recursively)
        # note f is only filename and not path, use the following (as an example if you wanted to open the file)
        with open(os.path.join(root, filename)) as f:
            for line in f:
                print f
        pass

推荐阅读