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

2024-03-29 12:12:40 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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")

其输出为:

^{pr2}$

我只想:

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

Tags: 文件代码inimport目录forosroot
1条回答
网友
1楼 · 发布于 2024-03-29 12:12:40

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

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")

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

^{pr2}$

看起来可能是你想要的。在

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

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

相关问题 更多 >