Python,删除文件夹中超过X天的所有文件 [英] Python, Deleting all files in a folder older than X days

查看:56
本文介绍了Python,删除文件夹中超过X天的所有文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to write a python script to delete all files in a folder older than X days. This is what I have so far:

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))

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

When I run the script, I get:

Error2 - 系统找不到指定的文件,

并给出文件名.我做错了什么?

and it gives the filename. What am I doing wrong?

推荐答案

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

os.listdir() returns a list of bare filenames. These do not have a full path, so you need to combine it with the path of the containing directory. You are doing this when you go to delete the file, but not when you stat the file (or when you do isfile() either).

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

Easiest solution is just to do it once at the top of your loop:

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

现在 f 是文件的完整路径,您只需在任何地方使用 f(将您的 remove() 调用更改为仅使用 <代码>f也是).

Now f is the full path to the file and you just use f everywhere (change your remove() call to just use f too).

这篇关于Python,删除文件夹中超过X天的所有文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆