Python树形打印目录结构
Python 结构 目录 打印 树形
2023-09-11 14:16:59 时间
前言
这两天整理数据文件的时候发现,一层层的点击文件夹查看很繁琐,于是想写一个工具来递归打印出文件目录的树形结构,网上找了一些资料几乎都是使用的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
变量拼接的过程。
相关文章
- 第三百五十节,Python分布式爬虫打造搜索引擎Scrapy精讲—selenium模块是一个python操作浏览器软件的一个模块,可以实现js动态网页请求
- python rtsp
- Python 字符串_python 字符串截取_python 字符串替换_python 字符串连接
- Python - 利用pip管理包
- python特殊方法(魔术方法):使用_ _开头和结尾的方法。如: __str__() __init__() __repr__() __bool__() __len__() __gt__()
- Atitit python3.0 3.3 3.5 3.6 新特性 Python2.7新特性1Python 3_x 新特性1python3.4新特性1python3.5新特性1值得关注的新特性1Python3.6新特性2 Python2.7新特性Python 2.7的新特性 - 牛皮糖NewPtone - 博客园.html Python 3_x 新特性及10大变化_python_脚本之家.htm
- Python编程语言学习:python编程语言中重要函数讲解之map函数等简介、使用方法之详细攻略
- Python语言学习之字符串那些事:python和字符串的使用方法之详细攻略
- Python之sklearn-pmml:sklearn-pmml的简介、安装、使用方法之详细攻略
- Py之matplotlib:python包之matplotlib库图表绘制包的简介、安装、使用方法(matplotlib颜色大全)详细攻略
- 蓝桥杯官网 试题 PREV-261 历届真题 循环小数【第十一届】【决赛】【研究生组】【C++】【C】【Java】【Python】四种解法
- Python每日一练(数据分析篇)——第32天:数据索引
- 【Python成长之路】python 基础篇 -- global/nonlocal关键字使用
- windows下使用pip安装python模块lxml
- python 将一个JSON 字典转换为一个Python 对象
- Python: 合并多个字典
- python基础6--目录结构
- 雅虎财经数据python 网络爬虫stock股票 用 Python 通过雅虎财经获取股票数据
- Python 环境搭建
- python编程自学心得和避坑经验
- opencv-python视频处理之录制视频