Python 使用 glob 和 os 模块通过通配符删除文件的实现方法

拾光
拾光
发布时间:2026-10-13 | 5人浏览过
原创

本文介绍了在 Python 中利用 glob 和 os 模块,通过通配符匹配并删除指定目录下文件的方法。代码示例展示了如何编写函数以支持当前目录及子目录的文件查找与删除操作,并提供了开启显示模式的调试选项。

具体实现代码如下所示:

# -*- 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 相关产品和应用

全部下载

专题列表