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