首页 > 解决方案 > Python获取最新文件列表并将其与旧文件列表进行比较

问题描述

目标

每 30 分钟从目标目录获取最新文件列表

我的解决方案(如果您知道更好,请告诉我)

  1. 每 30 分钟从目标目录获取文件列表。
  2. 将当前文件与新文件列表进行比较
  3. 制作最新文件的新列表。

问题

  1. 每 30 分钟从目标目录获取文件列表。

在这里我不知道如何获取当前和 30 分钟后的列表?

这里函数返回列表。

from os import listdir
from os.path import isfile, join


    def getFileNames(mypath):
        onlyfiles = [f for f in listdir(mypath) if isfile(join(mypath, f))]
        return onlyfiles

标签: pythonpython-3.xlistfilesystems

解决方案


以下是在 Python 中每 30 分钟检查一次新文件的方法:

from os import listdir
from os.path import isfile, join
from time import sleep


def getFileNames(mypath):
    onlyfiles = [f for f in listdir(mypath) if isfile(join(mypath, f))]
    return onlyfiles

folder = "/tmp" #location of temp files on Linux
old = getFileNames(folder)
while True:
    sleep(1800) #30 minutes
    new = getFileNames(folder)
    newFiles = [f for f in new if f not in old]
    print(newFiles)
    old = new

推荐阅读