首页 > 解决方案 > 删除文件夹和所有子文件夹中python中的文件类型

问题描述

我正在用 Python 编写脚本,需要清理才能在最后运行。我需要做的是删除任何 .ZIP 文件

我使用以下脚本在第一个文件夹上实现了这一点。

print("Deleting all .ZIP files")
dir_name =  os.path.expanduser("~") + "/AWSSplunk/Downloads/"
test = os.listdir(dir_name)

for item in test:
    if item.endswith(".zip"):
        os.remove(os.path.join(dir_name, item))
print("Deleting .ZIP files completed")

但是,我还需要删除其他子目录中的这些 .ZIP 文件 - 我怎样才能让它逐步通过该位置的子目录删除这些文件。

标签: python

解决方案


使用glob模块:

import glob

for file in glob.glob("**/*.zip", recursive=True):
    # delete file

推荐阅读