how to get files changed in last 5 minutes

Question:

Need to walk the current directory and get the files modified in last 5 mins. I am only starting this and this is what i have so far

#!/usr/bin/python

import os,sys,time

dir = os.getcwd() 

print dir


for f in os.walk(dir):
    for i in os.stat(f).st_mtime:
    print i

when i run this i get this error

for i in os.stat(f).st_mtime:

TypeError: coercing to Unicode: need string or buffer, tuple found

I would like to understand whats causing this before i move on

Asked By: johndoe12345

||

Answers:

os.walk() generates tuples, you’re trying to use a string. You want something like:

for root, dirs, files in walk(wav_root):
    for f in files:
        filename = root + f
        # Now use filename to call stat().st_mtime

I believe. Wherever you are while iterating with os.walk(), joining root and f will produce the absolute path IIRC.

See here for more: http://www.tutorialspoint.com/python/os_walk.htm

Answered By: Will

You need to unpack, join the file to the root directory and compare:

import os, time

_dir = os.getcwd()
files = (fle for rt, _, f in os.walk(_dir) for fle in f if time.time() - os.stat(
    os.path.join(rt, fle)).st_mtime < 300)

print(list(files))

os.stat(filename).st_mtime returns a time which cannot be iterated over, you need to compare that time to the current time, time.time() itself returns the seconds since the epoch so you need to compare the difference between time.time() - os.stat(os.path.join(rt, fle)).st_mtime to the amount of minutes in seconds, i.e 300 in your case.

If you are monitoring directories you might find watchdog useful, the example in the docs does exactly what you want:

import sys
import time
import logging
from watchdog.observers import Observer
from watchdog.events import LoggingEventHandler

if __name__ == "__main__":
    logging.basicConfig(level=logging.INFO,
                        format='%(asctime)s - %(message)s',
                        datefmt='%Y-%m-%d %H:%M:%S')
    path = sys.argv[1] if len(sys.argv) > 1 else '.'
    event_handler = LoggingEventHandler()
    observer = Observer()
    observer.schedule(event_handler, path, recursive=True)
    observer.start()
    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        observer.stop()
    observer.join()

It checks the current directory recursively for changes to files and logs any changes to the console.

Answered By: Padraic Cunningham

Try using the ‘os’, ‘glob’ and ‘time’ libraries:

import os
import glob
import time

file_list = glob.glob("C:\path_to_files\*.")
for file in file_list:
    if (int(time.time()) - int(os.stat(file).st_mtime) < 300):
        # Do something with this file
Answered By: DreamZeppelin
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.