Вопрос

I have a directory full of files that are generated every 5 minutes. When I do an ls -l at a cmd prompt I can see the files and their last modified time.

I need to programatically get a list of files that are timestamped within the last N minutes. How to do that?

Это было полезно?

Решение

Use os.path.getmtime or os.path.getctime to get modification / creation time of the file.

import os
import time

dirpath = '/path/to/dir'
past = time.time() - 2*60*60 # 2 hours
result = []
for p, ds, fs in os.walk(dirpath):
    for fn in fs:
        filepath = os.path.join(p, fn)
        if os.path.getmtime(filepath) >= past:
            result.append(filepath)

Другие советы

Note: The answer posted by falsetru recurses from dirpath down through all subdirs. to do this to a specific dir, dirpath in this case, use

import os
import time

dirpath = '/path/to/dir'
past = time.time() - 2*60*60 # 2 hours
result = []
result = [ f for f in listdir(dirpath) if ((isfile(join(dirpath,f))) and (os.path.getmtime(join(dirpath,f)) >= past)) ]
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top