前言
這兩天整理數據文件的時候發現,一層層的點擊文件夾查看很繁瑣,於是想寫一個工具來遞歸打印出文件目錄的樹形結構,網上找了一些資料幾乎都是使用的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.