Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get files changed in last 5 minutes

Tags:

python

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

like image 496
johndoe12345 Avatar asked Dec 19 '22 22:12

johndoe12345


2 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

like image 68
Will Avatar answered Jan 05 '23 21:01

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.

like image 26
Padraic Cunningham Avatar answered Jan 05 '23 20:01

Padraic Cunningham