连续删除 x 秒内未修改的文件夹中的 file/s

Deleting a file/s within a folder that hasn't been modified in x seconds, continuously

我有一个文件夹,其中包含不断更新的文本文件。我想删除早于 x 秒的文件,我可以通过以下方式做到这一点:

import os, time, sys
now = time.time()


def file_del(file1):
    try:
        if os.stat(os.path.join(path,file1)).st_mtime < now - 10:
            os.remove(os.path.join(path,file1))
    except FileNotFoundError as e:
        print(e)
        pass

path = "C:/Users/Username/Folder/"
x = os.listdir(path)

while True:
    for a in x:
        file_del(a)

上面的示例删除了超过 10 秒的文件。如果我 运行 现有文件上的脚本,但在脚本 运行ning.

时不操作添加到目录的新文件,则此方法有效

我希望它不断删除放置在目录中的文件,如果它们在 x 秒后未被修改。

我确定这是可能的,我只是觉得可能缺少一个循环?

如有任何help/further说明,我们将不胜感激,

编辑答案

    x = os.listdir(path)
    for a in x:
        now = time.time()
        file_del(a)

我在循环中没有 now 变量,所以每次迭代都使用相同的时间戳来删除文件。现在一切正常。

您需要继续刷新保存文件列表的变量。删除操作后将文件索引变量复制到 while 语句中:

import os, time, sys
now = time.time()


 def file_del(file1):
    try:
        if os.stat(os.path.join(path,file1)).st_mtime < now - 10:
            os.remove(os.path.join(path,file1))
    except FileNotFoundError as e:
        print(e)
        pass

path = "C:/Users/Username/Folder/"

x = os.listdir(path)

while True:
    for a in x:
        file_del(a)
        x = os.listdir(path)

我意识到我的错误:

修改时间是在函数第一次调用时捕获的,每次都需要运行。我将 now 变量添加到 while True 循环中,并且所有工作都按预期进行:

while True:
    x = os.listdir(path)
    for a in x:
        now = time.time()
        file_del(a)

感谢您的帮助,请建议是否应删除问题。