利用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环境配置及项目建立
Jun 30 Python
PyTorch CNN实战之MNIST手写数字识别示例
May 29 Python
python实现时间o(1)的最小栈的实例代码
Jul 23 Python
python pandas消除空值和空格以及 Nan数据替换方法
Oct 30 Python
详解Python logging调用Logger.info方法的处理过程
Feb 12 Python
详解Python使用Plotly绘图工具,绘制甘特图
Apr 02 Python
打包PyQt5应用时的注意事项
Feb 14 Python
Python datetime 格式化 明天,昨天实例
Mar 02 Python
关于Python Tkinter Button控件command传参问题的解决方式
Mar 04 Python
使用npy转image图像并保存的实例
Jul 01 Python
python中xlutils库用法浅析
Dec 29 Python
Python经常使用的一些内置函数
Apr 11 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代码
2006/12/06 PHP
PHP中,文件上传
2006/12/06 PHP
浅谈PHP变量作用域以及地址引用问题
2013/12/27 PHP
php实现信用卡校验位算法THE LUHN MOD-10示例
2014/05/07 PHP
php字符串分割函数用法实例
2015/03/17 PHP
PHP开发api接口安全验证操作实例详解
2020/03/26 PHP
使用jQuery模板来展现json数据的代码
2010/10/22 Javascript
JQuery each()嵌套使用小结
2014/04/18 Javascript
JavaScript生成的动态下雨背景效果实现方法
2015/02/25 Javascript
JavaScript+html5 canvas绘制渐变区域完整实例
2016/01/26 Javascript
Node.js和Express简单入门介绍
2017/03/24 Javascript
Angular 2.0+ 的数据绑定的实现示例
2017/08/09 Javascript
详解ES6 export default 和 import语句中的解构赋值
2019/05/28 Javascript
layui 关闭open弹出框 刷新table表格页面的方法
2019/09/16 Javascript
vue路由跳转传递参数的方式总结
2020/05/10 Javascript
如何在Vue中使localStorage具有响应式(思想实验)
2020/07/14 Javascript
[45:38]DOTA2上海特级锦标赛主赛事日 - 1 胜者组第一轮#1Liquid VS Alliance第一局
2016/03/02 DOTA
Python中使用logging模块打印log日志详解
2015/04/05 Python
Python2.7编程中SQLite3基本操作方法示例
2017/08/09 Python
Python内置函数—vars的具体使用方法
2017/12/04 Python
python获取文件真实链接的方法,针对于302返回码
2018/05/14 Python
多个应用共存的Django配置方法
2018/05/30 Python
pycharm远程linux开发和调试代码的方法
2018/07/17 Python
python 实现数字字符串左侧补零的方法
2018/12/04 Python
Django web框架使用url path name详解
2019/04/29 Python
pyqt5 实现在别的窗口弹出进度条
2019/06/18 Python
详解python命令提示符窗口下如何运行python脚本
2020/09/11 Python
Python-split()函数实例用法讲解
2020/12/18 Python
德国童装购物网站:NICKI´S.com
2018/04/20 全球购物
伦敦剧院及景点门票:Encore Tickets
2018/07/01 全球购物
大学本科毕业生求职信范文
2013/12/18 职场文书
社区平安建设汇报材料
2014/08/14 职场文书
商场父亲节活动方案
2014/08/27 职场文书
党员民主生活会材料
2014/12/15 职场文书
python四个坐标点对图片区域最小外接矩形进行裁剪
2021/06/04 Python
Springboot如何使用logback实现多环境配置?
2021/06/16 Java/Android