利用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使用ntplib库同步校准当地时间的方法
Jul 02 Python
Python实现Sqlite将字段当做索引进行查询的方法
Jul 21 Python
深入理解Python中变量赋值的问题
Jan 12 Python
Python中easy_install 和 pip 的安装及使用
Jun 05 Python
Odoo中如何生成唯一不重复的序列号详解
Feb 10 Python
python中format()函数的简单使用教程
Mar 14 Python
django框架防止XSS注入的方法分析
Jun 21 Python
基于python实现的百度音乐下载器python pyqt改进版(附代码)
Aug 05 Python
Python 图像对比度增强的几种方法(小结)
Sep 25 Python
Django2 连接MySQL及model测试实例分析
Dec 10 Python
PyQt5 closeEvent关闭事件退出提示框原理解析
Jan 08 Python
python库sklearn常用操作
Aug 23 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/10/09 PHP
封装一个PDO数据库操作类代码
2009/09/09 PHP
PHP 柱状图实现代码
2009/12/04 PHP
学习php笔记 字符串处理
2010/10/19 PHP
php获得网站访问统计信息类Compete API用法实例
2015/04/02 PHP
PHP框架性能测试报告
2016/05/08 PHP
yii2控制器Controller Ajax操作示例
2016/07/23 PHP
php微信开发接入
2016/08/27 PHP
ThinkPHP实现分页功能
2017/04/28 PHP
JavaScript 操作键盘的Enter事件(键盘任何事件),兼容多浏览器
2010/10/11 Javascript
JavaScript将当前时间转换成UTC标准时间的方法
2015/04/06 Javascript
JS设置下拉列表框当前所选值的方法
2015/12/22 Javascript
12个非常实用的JavaScript小技巧【推荐】
2016/05/18 Javascript
jQuery Ajax 异步加载显示等待效果代码分享
2016/08/01 Javascript
js 打开新页面在屏幕中间的实现方法
2016/11/02 Javascript
jQuery中on方法使用注意事项详解
2017/02/15 Javascript
Angular实现预加载延迟模块的示例
2017/10/12 Javascript
JS正则表达式完美实现身份证校验功能
2017/10/18 Javascript
微信小程序在线客服自动回复功能(基于node)
2019/07/03 Javascript
vue中input的v-model清空操作
2019/09/06 Javascript
[49:08]完美世界DOTA2联赛PWL S2 LBZS vs FTD.C 第一场 11.27
2020/12/01 DOTA
用Python脚本来删除指定容量以上的文件的教程
2015/05/04 Python
Python编程中用close()方法关闭文件的教程
2015/05/24 Python
深入解析Python编程中JSON模块的使用
2015/10/15 Python
关于Python中空格字符串处理的技巧总结
2017/08/10 Python
使用Python检测文章抄袭及去重算法原理解析
2019/06/14 Python
python爬虫之爬取百度音乐的实现方法
2019/08/24 Python
python代码xml转txt实例
2020/03/10 Python
Linux的文件类型
2012/03/07 面试题
就业推荐表自我鉴定范文
2014/03/21 职场文书
春节联欢会主持词
2014/03/24 职场文书
博士生求职信
2014/07/06 职场文书
节约每一滴水演讲稿
2014/09/09 职场文书
2014基层党员批评与自我批评范文
2014/09/24 职场文书
2019秋季运动会口号
2019/06/25 职场文书
给原生html中添加水印遮罩层的实现示例
2021/04/02 Javascript