利用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中的一些陷阱与技巧小结
Jul 10 Python
python正则表达式爬取猫眼电影top100
Feb 24 Python
python+pyqt5实现24点小游戏
Jan 24 Python
pymongo中聚合查询的使用方法
Mar 22 Python
六行python代码的爱心曲线详解
May 17 Python
如何用Python做一个微信机器人自动拉群
Jul 03 Python
信号生成及DFT的python实现方式
Feb 25 Python
Python -m参数原理及使用方法解析
Aug 21 Python
python链表类中获取元素实例方法
Feb 23 Python
为了顺利买到演唱会的票用Python制作了自动抢票的脚本
Oct 16 Python
Python调用腾讯API实现人脸身份证比对功能
Apr 04 Python
Python函数对象与闭包函数
Apr 13 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连接及读取和写入mysql数据库的常用代码
2014/08/11 PHP
php的debug相关函数用法示例
2016/07/11 PHP
php多进程模拟并发事务产生的问题小结
2018/12/07 PHP
教您去掉ie网页加载进度条的方法
2010/12/09 Javascript
JS 控件事件小结
2012/10/31 Javascript
jquery 动态创建元素的方式介绍及应用
2013/04/21 Javascript
JavaScript运行过程中的“预编译阶段”和“执行阶段”
2015/12/16 Javascript
jQuery选择器实例应用
2017/01/05 Javascript
NodeJS仿WebApi路由示例
2017/02/28 NodeJs
基于vue-video-player自定义播放器的方法
2018/03/21 Javascript
Js代码中的span拼接问题解决
2019/11/22 Javascript
[00:35]DOTA2上海特级锦标赛 MVP.Phx战队宣传片
2016/03/04 DOTA
使用IPython下的Net-SNMP来管理类UNIX系统的教程
2015/04/15 Python
栈和队列数据结构的基本概念及其相关的Python实现
2015/08/24 Python
简单学习Python多进程Multiprocessing
2017/08/29 Python
Python跨文件全局变量的实现方法示例
2017/12/10 Python
基于Python Numpy的数组array和矩阵matrix详解
2018/04/04 Python
对python中类的继承与方法重写介绍
2019/01/20 Python
python实战串口助手_解决8串口多个发送的问题
2019/06/12 Python
python实现LBP方法提取图像纹理特征实现分类的步骤
2019/07/11 Python
使用Python将字符串转换为格式化的日期时间字符串
2019/09/01 Python
使用 Python 合并多个格式一致的 Excel 文件(推荐)
2019/12/09 Python
pandas的resample重采样的使用
2020/04/24 Python
推荐10个CSS3 制作的创意下拉菜单效果
2014/02/11 HTML / CSS
用CSS3的box-reflect来制作倒影效果
2016/11/15 HTML / CSS
美国潜水装备、水肺潜水和浮潜设备商店:Leisure Pro
2018/08/08 全球购物
会计职业生涯规划范文
2014/01/04 职场文书
车贷收入证明范本
2014/01/09 职场文书
简历里的自我评价范文
2014/02/24 职场文书
支部组织生活会方案
2014/06/10 职场文书
爱耳日宣传活动总结
2014/07/05 职场文书
效能风暴心得体会
2014/09/04 职场文书
小学中等生评语
2014/12/29 职场文书
服装区域经理岗位职责
2015/04/10 职场文书
《分数的意义》教学反思
2016/02/20 职场文书
“鬼灭之刃”热度不减,其成功背后的原因是什么?
2022/03/22 日漫