递归地跟随目录

2024-04-25 00:35:17 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我正在使用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

Tags: or文件importselffooosdefdir
1条回答
网友
1楼 · 发布于 2024-04-25 00:35:17

使用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

相关问题 更多 >