网络编程
位置:首页>> 网络编程>> Python编程>> 利用Python查看目录中的文件示例详解

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

作者:RustFisher  发布时间:2023-02-06 14:13:28 

标签:python,目录,文件

前言

我们在日常开发中,经常会遇到一些关于文件的操作,例如,实现查看目录内容的功能。类似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}

来源:http://rustfisher.github.io/2017/07/01/Python_note/Python-scan-file/

0
投稿

猜你喜欢

  • 本书的作者Douglas Crockford是JavaScript开发社区最知名的权威,JavaScript的发明人Brendan Eich
  • 无论是公司的同事还是外界的程序员朋友们,大部分人对JavaScript的高级应用不甚了解,已有的知识架构里会认为JavaScript仅仅是一
  • 数据库的使用过程中由于程序方面的问题有时候会碰到重复数据,重复数据导致了数据库部分设置不能正确设置……方法一以下为引用的内容:declare
  • 网站开发时经常需要在某个页面需要实现对大量图片的浏览,如果考虑流量的话,大可以像pconline一样每个页面只显示一张图片,让用户每看一张图
  • 本文实例讲述了Python设计模式之工厂方法模式。分享给大家供大家参考,具体如下:工厂方法模式(Factory Method Pattern
  • 比较喜欢python的装饰器, 试了下一种用法,通过装饰器来传递sql,并执行返回结果这个应用应该比较少为了方便起见,直接使用了ironpy
  • 1:为什么每个layout下都有个inlayout?我们将layout的宽/浮动等属性设置好之后,对于layout内的padding和mar
  • 网上有不少生成缩略图的ASP组件。若你的虚拟空间不支持注册新组件,可能会感觉自己的网站失色不少。心晴不才,结合网上资源写了个无组件生成缩略图
  • javascript曾一度被认为是玩具型的语言,因为它太容易上手,而且,javascript曾一度担任为web站点“打杂”的职责。直到Aja
  • 在工控应用上,返回的数据经常会以二进制的形成存储,而这些二进制数据又是以每4个bit表示一个十六进制的数据内容。解析的时候,往往是一个字节(
  • 介绍获取协程返回值的四种方式:1、通过ensure_future获取,本质是future对象中的result方2、使用loop自带的crea
  • PHP mysqli_set_charset()函数设置默认客户端字符集:<?php// 假定数据库用户名:root,密码:12345
  • 序言本文所提及的VTD-XML并非本文作者原创,作者只是对它进行介绍。问题通常当我们提起XML的使用时,最头痛的部分便是XML的verbos
  • Blackfriday是在Go中实现的Markdown处理器。您可以安全地输入用户提供的数据,速度快,支持通用扩展(表,智能标点符号替换等)
  • 这篇论坛文章(赛迪网技术社区)主要介绍了如何建立适当的索引实现查询优化的相关问题,具体内容请大家参考下文:索引(index)是除表之外另一重
  • 本文实例讲述了golang操作mongodb的方法。分享给大家供大家参考。具体实现方法如下:package mainimport (&nbs
  • 分布式编程的难点在于:1.服务器之间的通信,主节点如何了解从节点的执行进度,并在从节点之间进行负载均衡和任务调度;2.如何让多个服务器上的进
  • 此文刊登在《程序员》三月期,有删改提到安全问题,首先想到应付这些问题的应该是系统管理员以及后台开发工程师们,而前端开发工程师似乎离这些问题很
  • 数据库系统的安全性包括很多方面。由于很多情况下,数据库服务器容许客户机从网络上连接,因此客户机连接的安全对MySQL数据库安全有很重要的影响
  • html5的webAPI接口可以很轻松的使用短短的几行代码就实现点击按钮复制区域文本的功能,不需要依赖flash。代码如下:/* 创建ran
手机版 网络编程 asp之家 www.aspxhome.com