简体   繁体   English

递归地跟随目录树

[英]Recursively following a directory tree

So I'm working with Python and still pretty new at it, and I need to be able to traverse all folders within a directory, so if /foo contains /foo/bar and /foo/bar/foo I want to list all entries. 因此,我正在使用Python,但它仍然很新,我需要能够遍历目录中的所有文件夹,因此,如果/foo包含/foo/bar/foo/bar/foo我想列出所有条目。 So far I've created a class that works inside it's own file but when I try to import it I get an error stating TypeError: coercing to Unicode: need string or buffer, builtin_function_or_method found . 到目前为止,我已经创建了一个在其自己的文件中工作的类,但是当我尝试import它时,出现错误,指出TypeError: coercing to Unicode: need string or buffer, builtin_function_or_method found

Function is found in the file DirTree so I'm importing it via: 函数位于文件DirTree因此我通过以下方式导入它:

from DirTree import DirTrav

DirList = DirTrav(dir).returnList()

The code can be found below. 该代码可以在下面找到。

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

Use os.walk() : 使用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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM