如何使python删除脚本递归?

时间:2016-06-15 21:18:29

标签: python-2.7 recursion

我在Stack Overflow上找到了以下Python脚本。除了我需要递归意味着它还将删除子文件夹/文件之外,我让它无问题地工作。我怎么能这样做?

#Import the required Python modules
import os
import time
import sys

#Set the folder path for deletion
path = r"c:\Delete"

#Set the time variable for "now" to subtract 30 days from "now."
now = time.time()

#Loop through the files in the path and delete any older than 30 days!
for f in os.listdir(path):
     f = os.path.join(path, f)
     if os.stat(f).st_mtime < now - 30 * 86400:
          if os.path.isfile(f):
               os.remove(os.path.join(path, f))

1 个答案:

答案 0 :(得分:0)

使用os.walk(path)代替os.listdir(path)也会这样做,但会递归。试试吧。

当然,您必须获取子文件夹中文件的完整路径,请参阅我链接到的部分中的最后一个示例:

os.path.join(root, name)

root是从os.walk()返回的3元组中的第一个元素,name是第3个元素。

编辑:此处的完整示例(摘自链接页面):

# Delete everything reachable from the directory named in "top",
# assuming there are no symbolic links.
# CAUTION:  This is dangerous!  For example, if top == '/', it
# could delete all your disk files.
import os
for root, dirs, files in os.walk(top, topdown=False):
  for name in files:
    os.remove(os.path.join(root, name))
  for name in dirs:
    os.rmdir(os.path.join(root, name))

只需添加您的时间过滤,我认为它应该有效。