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

use*_*573 41 python python-2.7

我正在尝试编写一个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))
Run Code Online (Sandbox Code Playgroud)

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

Error2 - system cannot find the file specified,

它给出了文件名.我究竟做错了什么?

kin*_*all 19

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

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

f = os.path.join(path, f)
Run Code Online (Sandbox Code Playgroud)

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


Man*_*Ali 13

我以更充分的方式做到了

import os, time

path = "/home/mansoor/Documents/clients/AirFinder/vendors"
now = time.time()

for filename in os.listdir(path):
    filestamp = os.stat(os.path.join(path, filename)).st_mtime
    seven_days_ago = now - 7 * 86400
    if filestamp < seven_days_ago:
        print(filename)
Run Code Online (Sandbox Code Playgroud)


小智 10

你需要使用if os.stat(os.path.join(path, f)).st_mtime < now - 7 * 86400:而不是if os.stat(f).st_mtime < now - 7 * 86400:

我发现使用os.path.getmtime更方便:-

import os, time

path = r"c:\users\%myusername%\downloads"
now = time.time()

for filename in os.listdir(path):
    # if os.stat(os.path.join(path, filename)).st_mtime < now - 7 * 86400:
    if os.path.getmtime(os.path.join(path, filename)) < now - 7 * 86400:
        if os.path.isfile(os.path.join(path, filename)):
            print(filename)
            os.remove(os.path.join(path, filename))

Run Code Online (Sandbox Code Playgroud)


Jor*_*ley 9

你还需要给它一个路径,否则它会在cwd中看到......具有讽刺意味的是,你做了os.remove但没有别的......

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


Bil*_*ell 5

我认为新的pathlib与日期的arrow模块一起使代码更整洁。

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
Run Code Online (Sandbox Code Playgroud)
  • pathlib使列出目录内容,访问文件特征(例如创建时间)和获取完整路径变得容易。
  • 箭头使时间的计算更加轻松和整洁。

这是显示pathlib提供的完整路径的输出。(无需加入。)

C:\scratch\removeThem\four.txt
C:\scratch\removeThem\one.txt
C:\scratch\removeThem\three.txt
C:\scratch\removeThem\two.txt
Run Code Online (Sandbox Code Playgroud)