Python树形打印目录结构
2024-09-28 14:35:53
前言
这两天整理数据文件的时候发现,一层层的点击文件夹查看很繁琐,于是想写一个工具来递归打印出文件目录的树形结构,网上找了一些资料几乎都是使用的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.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
变量拼接的过程。
最新文章
- [WCF编程]7.实例上下文模式
- java内存空间详解
- net-snmp源码VS2013编译添加加密支持(OpenSSL)
- python3.4 or 3.x xlwt replaced with xlwt-future
- Yii2中自带分页类实现分页
- MySQL优化—工欲善其事,必先利其器之EXPLAIN
- SQL Server— 存在检测、建库、 建表、约束、外键、级联删除
- 【Grunt】
- Android 框架修炼-自己开发高效异步图片加载框架
- php 遍历一个文件夹下的所有文件和子文件夹
- POJ2251 Dungeon Master(bfs)
- 关于binary log那些事——认真码了好长一篇
- springboot(二十二)spring-boot使用AOP
- Go语言中的slice
- DES加密解密算法C语言代码实现
- Codeforces 510 E. Fox And Dinner
- 使用TuShare下载历史逐笔成交数据并生成1分钟线
- python学习之算法、自定义模块、系统标准模块(上)
- C语言编程的环境以及架构
- Oracle 11g用exp无法导出空表的处理方法
热门文章
- private static final Logger logger= LoggerFactory.getLogger(WhMainBusi.class);
- python-面向对象-13_文件
- Entity Framework学习 - 5.DB First执行时提示model没有key
- echart 设计宽度为百分比时,div撑不开
- AsyncStorage和Promise配合使用
- 线上MYSQL同步报错故障处理方法总结
- Windows 10正式版的历史版本
- Redis入门到高可用(十二)—— pipeline
- vue在页面嵌入别的页面或者是视频2
- aop 日志统一处理