Python 通配符删除文件的实例

yipeiwu_com6年前Python基础

实例如下所示:

# -*- coding: utf-8 -*-
"""
使用通配符,获取所有文件,或进行操作。
"""
import glob
import os
def files(curr_dir = '.', ext = '*.exe'):
  """当前目录下的文件"""
  for i in glob.glob(os.path.join(curr_dir, ext)):
    yield i
def all_files(rootdir, ext):
  """当前目录下以及子目录的文件"""
  for name in os.listdir(rootdir):
    if os.path.isdir(os.path.join(rootdir, name)):
      try:
        for i in all_files(os.path.join(rootdir, name), ext):
          yield i
      except:
        pass
  for i in files(rootdir, ext):
    yield i
def remove_files(rootdir, ext, show = False):
  """删除rootdir目录下的符合的文件"""
  for i in files(rootdir, ext):
    if show:
      print i
    os.remove(i)
def remove_all_files(rootdir, ext, show = False):
  """删除rootdir目录下以及子目录下符合的文件"""
  for i in all_files(rootdir, ext):
    if show:
      print i
    os.remove(i)
if __name__ == '__main__':
  remove_all_files('.', '*.o', show = True)
  # remove_all_files('.', '*.exe', show = True)
  remove_files('.', '*.exe', show = True)
  # for i in files('.','*.c'):
    # print i

以上这篇Python 通配符删除文件的实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Python上下文管理器类和上下文管理器装饰器contextmanager用法实例分析

本文实例讲述了Python上下文管理器类和上下文管理器装饰器contextmanager用法。分享给大家供大家参考,具体如下: 一. 什么是上下文管理器 上下文管理器是在Python2....

详谈python在windows中的文件路径问题

在使用python通过open()函数来打开文件的时候,传递绝对路径给open()的时候,发现路径参数的内容与想象中的有所出入: 由于windows的路径分隔符使用的是反斜杠\,它刚刚好...

Python实现i人事自动打卡的示例代码

Python实现i人事自动打卡的示例代码

我司使用的打卡软件是 i 人事,不过我这记性,经常漏了打卡签退,定了闹钟都会忘,今天又被老大屌了。于是准备抓一下签到接口,利用 crontab 来实现自动签到签退。 环境配置 这里使用的...

Django框架 查询Extra功能实现解析

extra extra(select=None, where=None, params=None, tables=None, order_by=None, select_pa...

Python基于xlrd模块操作Excel的方法示例

本文实例讲述了Python基于xlrd模块操作Excel的方法。分享给大家供大家参考,具体如下: 一、使用xlrd读取excel 1、xlrd的安装: pip install xlr...