利用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元组操作实例解析
Sep 23 Python
python在windows下实现ping操作并接收返回信息的方法
Mar 20 Python
python概率计算器实例分析
Mar 25 Python
Python对列表中的各项进行关联详解
Aug 15 Python
Python多进程库multiprocessing中进程池Pool类的使用详解
Nov 24 Python
书单|人生苦短,你还不用python!
Dec 29 Python
查看python安装路径及pip安装的包列表及路径
Apr 03 Python
python SVD压缩图像的实现代码
Nov 05 Python
pandas的相关系数与协方差实例
Dec 27 Python
Python实现桌面翻译工具【新手必学】
Feb 12 Python
浅谈sklearn中predict与predict_proba区别
Jun 28 Python
python如何写个俄罗斯方块
Nov 06 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/05/19 PHP
mac下Apache + MySql + PHP搭建网站开发环境
2014/06/02 PHP
Yii2中设置与获取别名的函数(setAlias和getAlias)用法分析
2016/07/25 PHP
用js实现随机返回数组的一个元素
2007/08/13 Javascript
JQUERY操作JSON实例代码
2010/02/09 Javascript
JavaScript strike方法入门实例(给字符串加上删除线)
2014/10/17 Javascript
json传值以及ajax接收详解
2016/05/24 Javascript
jQuery Mobile动态刷新页面样式的实现方法
2016/05/28 Javascript
关于动态生成dom绑定事件失效的原因及解决方法
2016/08/06 Javascript
JavaScript算法系列之快速排序(Quicksort)算法实例详解
2016/09/04 Javascript
Angular ng-repeat遍历渲染完页面后执行其他操作详细介绍
2016/12/13 Javascript
JS简单实现移动端日历功能示例
2016/12/28 Javascript
微信小程序 简单教程实例详解
2017/01/13 Javascript
认识less和webstrom的less配置方法
2017/08/02 Javascript
轻松搞定jQuery+JSONP跨域请求的解决方案
2018/03/06 jQuery
解决vue-cli创建项目的loader问题
2018/03/13 Javascript
使用nvm和nrm优化node.js工作流的方法
2019/01/17 Javascript
vue视频播放暂停代码
2019/11/08 Javascript
OpenLayers3实现测量功能
2020/09/25 Javascript
详解vue 组件注册
2020/11/20 Vue.js
vue 基于abstract 路由模式 实现页面内嵌的示例代码
2020/12/14 Vue.js
[02:28]DOTA2英雄基础教程 灰烬之灵
2013/12/19 DOTA
全面了解Python环境配置及项目建立
2016/06/30 Python
python Tkinter的图片刷新实例
2019/06/14 Python
python使用原始套接字发送二层包(链路层帧)的方法
2019/07/22 Python
python使用socket 先读取长度,在读取报文内容示例
2019/09/26 Python
python多环境切换及pyenv使用过程详解
2019/09/27 Python
Amara美国站:英国高端家居礼品网站,世界各地的奢侈家具品牌
2017/07/26 全球购物
参观考察邀请函范文
2014/01/29 职场文书
大学毕业寄语大全
2014/04/10 职场文书
《猴子种果树》教学反思
2014/04/26 职场文书
员工安全生产责任书
2014/07/22 职场文书
答谢词范文
2015/01/05 职场文书
班委竞选稿范文
2015/11/21 职场文书
Java日常练习题,每天进步一点点(38)
2021/07/26 Java/Android
MySQL学习必备条件查询数据
2022/03/25 MySQL