Python 获取指定文件夹下的目录和文件的实现


Posted in Python onAugust 30, 2019

经常有需要扫描目录,对文件做批量处理的需求,所以对目录处理这块做了下学习和总结。Python 中扫描目录有两种方法:os.listdir 和 os.walk。

一、os.listdir 方法

os.listdir() 方法用于返回指定的目录下包含的文件或子目录的名字的列表。这个列表以字母顺序。其得到的是仅当前路径下的文件名,不包括子目录中的文件,如果需要得到所有文件需要递归。 它也不包括 '.' 和 '..' 即使它在目录中。

语法格式如下:

os.listdir(path)

实例代码

def list_dir(file_dir):
  '''
    通过 listdir 得到的是仅当前路径下的文件名,不包括子目录中的文件,如果需要得到所有文件需要递归
  '''
  print'\n\n<><><><><><> listdir <><><><><><>'
  print "current dir : {0}".format(file_dir)
  dir_list = os.listdir(file_dir)
  for cur_file in dir_list:
    # 获取文件的绝对路径
    path = os.path.join(file_dir, cur_file)
    if os.path.isfile(path): # 判断是否是文件还是目录需要用绝对路径
      print "{0} : is file!".format(cur_file)
    if os.path.isdir(path):
      print "{0} : is dir!".format(cur_file)
      list_dir(path) # 递归子目录

二、os.walk 方法

os.walk() 方法用于通过在目录树中游走输出在目录中的文件名,向上或者向下。是一个简单易用的文件、目录遍历器,可以帮助我们高效的处理文件、目录方面的事情。

语法格式如下:

os.walk(top[, topdown=True[, onerror=None[, followlinks=False]]])

方法参数说明:

  • top:要遍历的目录的路径
  • topdown:可选,如果为 True,则优先遍历 top 目录,以及 top 目录下的每一个子目录,否则优先遍历 top 的子目录,默认为 True
  • onerror: 可选, 需要一个 callable 对象,当 walk 异常时调用
  • followlinks:可选, 如果为 True,则会遍历目录下的快捷方式(linux 下是 symbolic link)实际所指的目录,默认为 False
  • args:包含那些没有 '-' 或 '--' 的参数列表

返回值: 三元组 (root, dirs, files)

  • root :所指的是当前正在遍历的目录的地址
  • dirs :当前文件夹中所有目录名字的 list (不包括子目录)
  • files :当前文件夹中所有的文件 (不包括子目录中的文件)

实例

def work_dir(file_dir):
  print'\n\n<><><><><> work dir <><><><><>'
  for root, dirs, files in os.walk(file_dir):
    print'\n========================================'
    print "root : {0}".format(root)
    print "dirs : {0}".format(dirs)
    print "files : {0}".format(files)
​
    for file in files:
      try:
        print'-----------------------------------'
        
        file_name = os.path.splitext(file)[0]
        file_suffix = os.path.splitext(file)[1]
        file_path = os.path.join(root, file)
        file_abs_path = os.path.abspath(file)
        file_parent = os.path.dirname(file_path)
​
        print "file : {0}".format(file)
        print "file_name : {0}".format(file_name)
        print "file_suffix : {0}".format(file_suffix)
        print "file_path : {0}".format(file_path)
        print "file_abs_path : {0}".format(file_abs_path)
        print "file_parent : {0}".format(file_parent)
        
      except Exception, e:
        print "Exception", e

三、其他跟文件相关的常用方法

os.path.splitext():分离文件名和扩展名

file = "file_test.txt"
file_name = os.path.splitext(file)[0] # 输出:file_test
file_suffix = os.path.splitext(file)[1] # 输出:.txt

os.path.exists():判断文件或目录是否存在

os.path.isfile():判断是否是文件

os.path.isdir():判断是否是目录

os.path.dirname():获取当前文件所在的目录,即父目录

os.makedirs():创建多级目录

os.mkdir():创建单级目录

os.path.getsize():获取文件大小

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Python 相关文章推荐
pymongo实现控制mongodb中数字字段做加法的方法
Mar 26 Python
python自然语言编码转换模块codecs介绍
Apr 08 Python
python获取list下标及其值的简单方法
Sep 12 Python
Mac 上切换Python多版本
Jun 17 Python
Django中Model的使用方法教程
Mar 07 Python
Python面向对象之静态属性、类方法与静态方法分析
Aug 24 Python
python3图片文件批量重命名处理
Oct 31 Python
tf.concat中axis的含义与使用详解
Feb 07 Python
Scrapy项目实战之爬取某社区用户详情
Sep 17 Python
浅谈Python numpy创建空数组的问题
May 25 Python
Matplotlib绘制混淆矩阵的实现
May 27 Python
Python游戏开发实例之graphics实现AI五子棋
Nov 01 Python
简单的Python调度器Schedule详解
Aug 30 #Python
详解在Python中以绝对路径或者相对路径导入文件的方法
Aug 30 #Python
Django使用uwsgi部署时的配置以及django日志文件的处理方法
Aug 30 #Python
Python matplotlib生成图片背景透明的示例代码
Aug 30 #Python
Python 批量刷博客园访问量脚本过程解析
Aug 30 #Python
快速解决docker-py api版本不兼容的问题
Aug 30 #Python
Python 使用 Pillow 模块给图片添加文字水印的方法
Aug 30 #Python
You might like
PHP5常用函数列表(分享)
2013/06/07 PHP
php生成QRcode实例
2014/09/22 PHP
父窗口获取弹出子窗口文本框的值
2006/06/27 Javascript
用JS剩余字数计算的代码
2008/07/03 Javascript
jQuery 1.2.x 升? 1.3.x 注意事项
2009/05/06 Javascript
Document.location.href和.replace的区别示例介绍
2014/03/04 Javascript
10分钟学会写Jquery插件实例教程
2014/09/06 Javascript
js实现温度计时间样式代码分享
2015/08/21 Javascript
JavaScript中数组添加值和访问值常见问题
2016/02/06 Javascript
9个让JavaScript调试更简单的Console命令
2016/11/14 Javascript
浅析bootstrap原理及优缺点
2017/03/19 Javascript
10道典型的JavaScript面试题
2017/03/22 Javascript
ionic3+Angular4实现接口请求及本地json文件读取示例
2017/10/11 Javascript
element form 校验数组每一项实例代码
2019/10/10 Javascript
原生js实现随机点名功能
2019/11/05 Javascript
利用Vue的v-for和v-bind实现列表颜色切换
2020/07/17 Javascript
3分钟学会一个Python小技巧
2018/11/23 Python
Python反爬虫技术之防止IP地址被封杀的讲解
2019/01/09 Python
在pycharm中使用git版本管理以及同步github的方法
2019/01/16 Python
pyqt5实现按钮添加背景图片以及背景图片的切换方法
2019/06/13 Python
pytorch 彩色图像转灰度图像实例
2020/01/13 Python
TensorFLow 不同大小图片的TFrecords存取实例
2020/01/20 Python
python实现从ftp服务器下载文件
2020/03/03 Python
写出SQL四条最基本的数据操作语句(DML)
2012/12/12 面试题
公司端午节活动方案
2014/02/04 职场文书
2014年机关植树节活动方案
2014/02/27 职场文书
服务理念口号
2014/06/11 职场文书
2014年初中班主任工作总结
2014/11/08 职场文书
七一建党节慰问信
2015/02/14 职场文书
2015年银行大堂经理工作总结
2015/04/24 职场文书
欢迎新生标语2015
2015/07/16 职场文书
创业计划书之健康营养产业
2019/10/15 职场文书
浅谈克隆 JavaScript
2021/11/02 Javascript
深入理解Pytorch微调torchvision模型
2021/11/11 Python
vue实现移动端div拖动效果
2022/03/03 Vue.js
Go微服务项目配置文件的定义和读取示例详解
2022/06/21 Golang