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

How to print only the subdirectory tree using python?

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

我有一个 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

您似乎不愿意更新您的问题以明确您想要什么,所以我猜测您只需要叶目录。你可以这样做:

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