【问题标题】:Delete file type in python in folder and all subfolders [duplicate]删除文件夹和所有子文件夹中python中的文件类型[重复]
【发布时间】:2020-01-29 12:28:28
【问题描述】:

我正在用 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


【解决方案1】:

使用glob 模块:

import glob

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

【讨论】:

  • 甚至可以使用pathlib 进行更现代的拍摄(加上 Path.glob 默认是递归的)
【解决方案2】:

你可以使用os.walk找到一个目录下的所有文件:

import os

your_list = list(os.walk('your_folder'))

【讨论】:

    猜你喜欢
    • 2012-04-01
    • 1970-01-01
    • 2019-07-02
    • 1970-01-01
    • 2017-07-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-21
    相关资源
    最近更新 更多