我试图用蟒蛇os.walk从任意目录glob的结构文件:的Python:os.walk()维持层次
matches = []
for root, dirnames, filenames in os.walk(path):
for filename in fnmatch.filter(filenames, name):
matches.append(os.path.join(root, filename))
print matches
这很好水珠的所有文件,但我想也能够保持实际的文件夹结构,即我想通过子文件夹走子文件夹,所以我真的知道什么文件名属于什么子文件夹。这是可能的与os.walk或我将不得不推出我自己的功能?
为了澄清我的问题:我想创建一个我解析的目录的程序内部树,所以我想实际上以递归的方式解析目录树,以便我偶然遇到每个子目录和文件,即:
伪代码:
def createAndParseSubDir(path):
ret = []
files = glob(path)
for file in files:
if isDir(file):
ret.append(createAndParseSubDir(file))
else:
ret.append(file)
return ret
hierarchy = createAndParseSubDir(myRoot)
编辑: 我结束了使用类似上面的伪代码类似的递归函数,以确保文件/迪尔斯以类似的方式树解析。
对[这个问题] [1]的接受答案解决了这个特殊问题。 [1]:http://stackoverflow.com/questions/2909975/python-list-directory-subdirectory-and-files – 2012-11-07 12:15:54