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
解决方案
使用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
推荐阅读
- cudnn - 如何使用指定的 cuda 和 cudnn 构建 caffe2?
- python - Django-Ajax:这是将数据返回给 Ajax 请求的最 Pythonic 的吗?
- python - Python 字典:运行自定义函数
- c# - 如何从平面缓冲区模式中的任何表中检索字段
- node.js - 通过不同属性进行动态查询(Node.js)
- java - log4j2 日志没有被写入文件
- matlab - 如何找到可以从 MATLAB 中的分区访问的单元分区?
- angular - 具有不同属性名称的 Typescript 映射类型
- c++ - 创建具有特定值的特定格式的 char*
- javascript - jQuery触发onDrop事件反应节点