如何使用python只打印子目录树?

时间:2016-02-11 09:46:05

标签: python os.walk

我有一个目录,其中包含许多子目录,在每个子目录中我都有一些子目录。

enter image description here

我有一个python代码,用于在文件中打印和写入目录和子目录。代码:

import os
file = open("list", "w")
for root, dirs, files in os.walk("./customers/"):
   print root
   file.write(root+"\n")

输出为:

./customers/A
./customers/A1
./customers/A2
./customers/B
./customers/B1
./customers/B2
./customers/C
./customers/C1
./customers/C2

我只想:

./customers/A1
./customers/A2
./customers/B1
./customers/B2
./customers/C1
./customers/C2

1 个答案:

答案 0 :(得分:0)

您似乎不愿意更新您的问题以明确您想要的内容,因此我猜测您只想要叶子目录。你可以这样做:

import os

with open('list', 'w') as outfile:
    for root, dirs, files in os.walk("./customers/"):
        if not dirs:    # if root has no sub-directories it's a leaf
            print root
            outfile.write(root+"\n")

对于您的目录结构,应该输出:

./customers/C/C2
./customers/C/C1
./customers/B/B2
./customers/B/B1
./customers/A/A2
./customers/A/A1

看起来像可能就是你想要的。

如果您希望输出排序,您可以编写生成器函数并对其输出进行排序:

import os

def find_leaf_directories(top):
    for root, dirs, files in os.walk(top):
        if not dirs:    # if root has no sub-directories it's a leaf
            yield root

with open('list', 'w') as outfile:
    for dir in sorted(find_leaf_directories('./customers/')):
        print dir
        outfile.write(dir+"\n")

将输出:

./customers/A/A1
./customers/A/A2
./customers/B/B1
./customers/B/B2
./customers/C/C1
./customers/C/C2