利用Python查看目录中的文件示例详解


Posted in Python onAugust 28, 2017

前言

我们在日常开发中,经常会遇到一些关于文件的操作,例如,实现查看目录内容的功能。类似Linux下的tree命令。统计目录下指定后缀文件的行数。

功能是将目录下所有的文件路径存入list中。可以加入后缀判断功能,搜索指定的后缀名文件。主要利用递归的方法来检索文件。

仿造 tree 功能示例代码

Python2.7

列出目录下所有文件

递归法

import os
def tree_dir(path, c_path='', is_root=True):
 """
 Get file list under path. Like 'tree'
 :param path Root dir
 :param c_path Child dir
 :param is_root Current is root dir
 """
 res = []
 if not os.path.exists(path):
 return res
 for f in os.listdir(path):
 if os.path.isfile(os.path.join(path, f)):
  if is_root:
  res.append(f)
  else:
  res.append(os.path.join(c_path, f))
 else:
  res.extend(tree_dir(os.path.join(path, f), f, is_root=False))
 return res

下面是加入后缀判断的方法。在找到文件后,判断一下是否符合后缀要求。不符合要求的文件就跳过。

def tree_dir_sur(path, c_path='', is_root=True, suffix=''):
 """ Get file list under path. Like 'tree'
 :param path Root dir
 :param c_path Child dir
 :param is_root Current is root dir
 :param suffix Suffix of file
 """
 res = []
 if not os.path.exists(path) or not os.path.isdir(path):
 return res
 for f in os.listdir(path):
 if os.path.isfile(os.path.join(path, f)) and str(f).endswith(suffix):
  if is_root:
  res.append(f)
  else:
  res.append(os.path.join(c_path, f))
 else:
  res.extend(tree_dir_sur(os.path.join(path, f), f, is_root=False, suffix=suffix))
 return res
if __name__ == "__main__":
 for p in tree_dir_sur(os.path.join('E:\ws', 'rnote', 'Python_note'), suffix='md'):
 print p

统计目录下指定后缀文件的行数

仅适用os中的方法,仅检索目录中固定位置的文件

# -*- coding: utf-8 -*-
import os
def count_by_categories(path):
 """ Find all target files and count the lines """
 if not os.path.exists(path):
 return
 c_l_dict = dict() # e.g. {category: lines}
 category_list = [cate for cate in os.listdir(path) if
   os.path.isdir(os.path.join(path, cate)) and not cate.startswith('.')]
 for category_dir in category_list:
 line_count = _sum_total_line(os.path.join(path, category_dir), '.md')
 if line_count > 0:
  c_l_dict[category_dir] = line_count
 return c_l_dict
def _sum_total_line(path, endswith='.md'):
 """ Get the total lines of target files """
 if not os.path.exists(path) or not os.path.isdir(path):
 return 0
 total_lines = 0
 for f in os.listdir(path):
 if f.endswith(endswith):
  with open(os.path.join(path, f)) as cur_f:
  total_lines += len(cur_f.readlines())
 return total_lines
if __name__ == '__main__':
 note_dir = 'E:/ws/rnote'
 ca_l_dict = count_by_categories(note_dir)
 all_lines = 0
 for k in ca_l_dict.keys():
 all_lines += ca_l_dict[k]
 print 'all lines:', str(all_lines)
 print ca_l_dict

以笔记文件夹为例,分别统计分类目录下文件的总行数,测试输出

all lines: 25433
{'flash_compile_git_note': 334, 'Linux_note': 387, 'Algorithm_note': 3637, 'Comprehensive': 216, 'advice': 137, 'Java_note': 3013, 'Android_note': 11552, 'DesignPattern': 2646, 'Python_note': 787, 'kotlin': 184, 'cpp_note': 279, 'PyQt_note': 439, 'reading': 686, 'backend': 1136}

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流,谢谢大家对三水点靠木的支持。

Python 相关文章推荐
Python功能键的读取方法
May 28 Python
Python与R语言的简要对比
Nov 14 Python
利用django-suit模板添加自定义的菜单、页面及设置访问权限
Jul 13 Python
Python实现Dijkstra算法
Oct 17 Python
Python3自动签到 定时任务 判断节假日的实例
Nov 13 Python
python实现归并排序算法
Nov 22 Python
python实现连续图文识别
Dec 18 Python
Python-Flask:动态创建表的示例详解
Nov 22 Python
Python-opencv 双线性插值实例
Jan 17 Python
pycharm下配置pyqt5的教程(anaconda虚拟环境下+tensorflow)
Mar 25 Python
查看jupyter notebook每个单元格运行时间实例
Apr 22 Python
python 实现mysql自动增删分区的方法
Apr 01 Python
Python如何通过subprocess调用adb命令详解
Aug 27 #Python
Python中序列的修改、散列与切片详解
Aug 27 #Python
Python正确重载运算符的方法示例详解
Aug 27 #Python
深入学习Python中的上下文管理器与else块
Aug 27 #Python
python利用MethodType绑定方法到类示例代码
Aug 27 #Python
Python中使用haystack实现django全文检索搜索引擎功能
Aug 26 #Python
python读取excel表格生成erlang数据
Aug 26 #Python
You might like
php 无限级分类学习参考之对ecshop无限级分类的解析 带详细注释
2010/03/23 PHP
根据中文裁减字符串函数的php代码
2013/12/03 PHP
在PHP站点的页面上添加Facebook评论插件的实例教程
2016/01/08 PHP
PHP解压ZIP文件到指定文件夹的方法
2016/11/17 PHP
PHP正则表达式匹配替换与分割功能实例浅析
2017/02/04 PHP
js 分栏效果实现代码
2009/08/29 Javascript
Javascript 中文字符串处理额外注意事项
2009/11/15 Javascript
JavaScript高级程序设计 扩展--关于动态原型
2010/11/09 Javascript
Jquery+CSS3实现一款简洁大气带滑动效果的弹出层
2013/05/15 Javascript
XML文件转化成NSData对象的方法
2015/08/12 Javascript
浅析Bootstrip的select控件绑定数据的问题
2016/05/10 Javascript
jQuery插件制作的实例教程
2016/05/16 Javascript
使用jquery提交form表单并自定义action的方法
2016/05/25 Javascript
JS常用字符串方法(推荐)
2021/01/15 Javascript
Bootstrap栅格系统学习笔记
2016/11/25 Javascript
JavaScript利用正则表达式替换字符串中的内容
2016/12/12 Javascript
bootstrap按钮插件(Button)使用方法解析
2017/01/13 Javascript
移动端(微信等使用vConsole调试console的方法
2019/03/05 Javascript
vue19 组建 Vue.extend component、组件模版、动态组件 的实例代码
2019/04/04 Javascript
python进阶教程之异常处理
2014/08/30 Python
Python随机生成一个6位的验证码代码分享
2015/03/24 Python
详解Python中的type()方法的使用
2015/05/21 Python
Python探索之爬取电商售卖信息代码示例
2017/10/27 Python
python实现数据导出到excel的示例--普通格式
2018/05/03 Python
解决python给列表里添加字典时被最后一个覆盖的问题
2019/01/21 Python
Python使用Chrome插件实现爬虫过程图解
2020/06/09 Python
具有防紫外线功能的高性能钓鱼服装:Hook&Tackle
2018/08/16 全球购物
马云的职业生涯规划之路
2014/01/01 职场文书
会计电算化大学生职业规划书
2014/02/05 职场文书
中专毕业生个人职业生涯规划
2014/02/19 职场文书
公证书样本
2014/04/10 职场文书
用python批量解压带密码的压缩包
2021/05/31 Python
SQL实现LeetCode(175.联合两表)
2021/08/04 MySQL
世界十大狙击步枪排行榜
2022/03/20 杂记
Golang 字符串的常见操作
2022/04/19 Golang
Ubuntu Server 安装Tomcat并配置systemctl
2022/04/28 Servers