Python学习笔记(2)——遍历目录结构并打印
来源:互联网 发布:2007年美国进出口数据 编辑:程序博客网 时间:2024/06/04 18:02
有时候想看一下项目中的目录和文件结构,用python实现
主要用到这几个函数
import os
os.getcwd() #获取当前运行程序的目录
os.listdir(path) #取得path下的文件和目录,返回值List类型
os.path.isdir(path) #判断path路径是否为目录
os.path.isfile(path)#判断path路径是否为文件
os.path.splitext(path)#对path路径切片,第二个为文件拓展名,例如'.py'
代码如下
import os#只打印以下文件拓展名cType = ['.py','.html','.css','.js','.sql']def show_file(path,deep): #取得当前目录下的文件夹以及文件,返回值List类型 file_list = os.listdir(path) #实现遍历目录 for dir in file_list: if os.path.isdir(path+'/'+dir): if deep == 0: print dir+'/' else: print '| '*deep+'+-'+dir+'/' #递归打印 show_file(path+'/'+dir,deep+1) #实现遍历文件 for file in file_list: if os.path.isfile(path+'/'+file): #过滤文件 for type in cType: #对路径切片获得文件拓展名 if os.path.splitext(path+'/'+file)[1] == type: if deep == 0: print file else: print '| '*deep+'+-'+file break;if __name__ == '__main__': path = os.getcwd() print path show_file(path,0)
例如打印某一目录结构:
/web/mycode/python/learn_webserving_xml/| +-templates/| +-code.py| +-__init__.pybasic_blog/| +-templates/| | +-new.html| | +-base.html| | +-index.html| | +-edit.html| | +-view.html| | +-login.html| +-scheme.sql| +-model.py| +-blog.py| +-__init__.pytodo_list/| +-templates/| | +-base.html| | +-index.html| | +-admin.html| +-model.py| +-schema.sql| +-todo.py| +-__init__.py
方法二:
# coding=utf-8__author__ = 'nianyu'from os.path import basename, isdir, existsfrom os import listdirfrom sys import argvdef show_tree(path,depth=0): print depth* '| ' + '|_', basename(path) if(isdir(path)): for item in listdir(path): show_tree(path+'/'+item, depth+1)def isExist(path): if path[0] is not '/': return False if not exists(path): return False return Trueif __name__ == "__main__": args = argv if len(args)>2: print "more than one argument." exit(0) path = str(args[1]) if not isExist(path): print "the file path do not exist." exit(0) # show_tree("./") show_tree(path)
0 0
- Python学习笔记(2)——遍历目录结构并打印
- Python 遍历目录并打印出子目录的大小
- python学习笔记(六)目录遍历,异常处理
- Python学习笔记(21)-目录遍历
- Python树形打印目录结构
- Android学习笔记(1)——HelloWorld目录结构
- php 遍历目录并打印所有文件名
- Python 遍历字典——学习笔记
- python学习笔记--打印嵌套list中每个数据(遍历列表)
- python 学习笔记(一)—目录文件的操作
- Python学习笔记之遍历目录文件(递归和walk())
- JavaWeb学习笔记—Tomcat目录结构以及JavaEE目录结构规范
- Linux学习笔记——linux目录结构及功能
- 学习笔记10——linux目录结构基础
- Linux学习笔记——Linux目录结构
- THINKPHP3.2学习笔记(1)目录结构
- 微信小程序学习笔记(2)--------框架之目录结构
- linux学习笔记2----目录结构
- 傅里叶变换
- 在CGI中如何使用cookie
- 【Arduino】开发入门教程【五】Hello Arduino
- CoreText
- 【Arduino】开发入门教程【六】数据类型转换函数
- Python学习笔记(2)——遍历目录结构并打印
- 【Arduino】开发入门【七】7段LED显示器
- 【Arduino】开发入门【八】舵机操作+源代码
- 【Arduino】开发入门【十】Arduino蓝牙模块与Android实现通信
- 三大框架的理解---笔记
- 【Arduino】开源开发板说明
- ios设备抓包方法
- C++STL常见面试题
- 用WebCollector下载在线API文档