所以我正在使用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
答案 0 :(得分:0)
使用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