脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Python - python实现树形打印目录结构

python实现树形打印目录结构

2021-01-25 00:32AlbertS Python

这篇文章主要为大家详细介绍了python树形打印目录结构的相关代码,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

本文实例为大家分享了python树形打印目录结构的具体代码,供大家参考,具体内容如下

前言

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

代码

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#!/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)

运行效果

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
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.jpg
| | +--169b1b76356f636.jpg
| | +--1a774de56fb4bf2.jpg
| | +--small_event_dft.jpg
| | +--ypy_qr.jpg
| +--crawler_image_test.py
| +--crawler_test.py
| +--crawler_website
| | +--crawler_article_set
| | | +--aiohttp.html
| | | +--asyncio.html
| | | +--async_await.html
| | | +--base64.html

总结

  • 一开始写的时候发现只能递归一层文件夹,后来发现问题出现在os.path.isdir函数这里。
  • 传给os.path.isdir函数函数的参数只能是一个绝对路径,或者相对于工作目录的相对路径。
  • 有了上面发现的问题,才有了newitem变量拼接的过程。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。

原文链接:https://blog.csdn.net/albertsh/article/details/77886876

延伸 · 阅读

精彩推荐