wangshicheng

前言

这两天整理数据文件的时候发现,一层层的点击文件夹查看很繁琐,于是想写一个工具来递归打印出文件目录的树形结构,网上找了一些资料几乎都是使用的os.walk, 调试了以后发现返回的貌似的是一个“生成器”,只需要for循环即可,可是这样得到的好像是BFS的结构,并不是我想要的树形结构,最后终于发现了os.listdir这个函数,可是使用它来写一个深度优先搜索,只要递归调用就能解决我的问题。

代码

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#a test for traverse directory

__author__ = \'AlbertS\'

import os
import os.path

def dfs_showdir(path, depth):
    if depth == 0:
        print("root:[" + path + "]")

    for item in os.listdir(path):
        if \'.git\' not in item:
            print("| " * depth + "+--" + item)

            newitem = path +\'/\'+ item
            if os.path.isdir(newitem):
                dfs_showdir(newitem, depth +1)

if __name__ == \'__main__\':
    dfs_showdir(\'.\', 0)

运行效果

root:[.]
+--1111.segmentfault.com
|      +--01decode.py
|      +--01string.txt
|      +--1111.segmentfault.com.tar.gz
+--urllib_test.py
+--use_module.py
+--water_deal
|      +--water_pouring2.py
+--web
|      +--module_test.py
|      +--__init__.py
|      +--__pycache__
|      |      +--module_test.cpython-34.pyc
|      |      +--__init__.cpython-34.pyc
+--web_crawler
|      +--bg_teaser.svg
|      +--crawler_images
|      |      +--10393478-1.jpg
|      |      +--13802226-1.

分类:

技术点:

相关文章: