Python,删除文件夹中超过X天的所有文件

2024-03-28 11:38:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图编写一个python脚本来删除文件夹中超过X天的所有文件。这就是我目前所拥有的:

import os, time, sys

path = r"c:\users\%myusername%\downloads"

now = time.time()

for f in os.listdir(path):

 if os.stat(f).st_mtime < now - 7 * 86400:

  if os.path.isfile(f):

   os.remove(os.path.join(path, f))

当我运行脚本时,我得到:

Error2 - system cannot find the file specified

它给出了文件名。我做错什么了?


Tags: 文件pathinimport脚本文件夹forif
3条回答

你还需要给它一条路径,否则它会在cwd中查找。。讽刺的是,你在os.remove上做了很多,但是没有其他地方。。。

for f in os.listdir(path):
    if os.stat(os.path.join(path,f)).st_mtime < now - 7 * 86400:

我认为新的pathlib和日期的箭头模块可以使代码更整洁。

from pathlib import Path
import arrow

filesPath = r"C:\scratch\removeThem"

criticalTime = arrow.now().shift(hours=+5).shift(days=-7)

for item in Path(filesPath).glob('*'):
    if item.is_file():
        print (str(item.absolute()))
        itemTime = arrow.get(item.stat().st_mtime)
        if itemTime < criticalTime:
            #remove it
            pass
  • pathlib使列出目录内容、访问文件特性(如创建时间)和获取完整路径变得容易。
  • 箭头使计算时间变得更简单、更整洁。

下面的输出显示了pathlib提供的完整路径。(无需加入。)

C:\scratch\removeThem\four.txt
C:\scratch\removeThem\one.txt
C:\scratch\removeThem\three.txt
C:\scratch\removeThem\two.txt

os.listdir()返回裸文件名列表。这些目录没有完整的路径,因此需要将其与包含目录的路径结合起来。当您要删除该文件时,您正在执行此操作,但当您stat该文件时(或者当您执行isfile()时)不会执行此操作。

最简单的解决方案是在循环的顶部执行一次:

f = os.path.join(path, f)

现在f是文件的完整路径,您只需在任何地方使用f(将您的remove()调用更改为只使用f)。

相关问题 更多 >