sar12089
sar12089

Reputation: 65

How to get the time of the last modified file in a folder using Python

I'm developing code in ODI. My need is to get the date/time of the last modified file in a directory and check if the date/time of the last modified file is greater than 5 minutes; then copy all the files in that folder to another folder. If it is less than 5 minutes, wait for 2 minutes and recheck again.

I have achieved of getting the date/time of the last modified file in a directory through .bat file. I'm storing the output in a .txt file and then loading that file in a temporary interface to check whether the time is greater than 5 minutes.

I want to achieve my requirement through Python script, because I hope it will be done in a single step of ODI Procedure.

Please help.

Thanks in advance

Upvotes: 0

Views: 2182

Answers (1)

glegoux
glegoux

Reputation: 3623

To remove the last modified file in a folder if it is older than 5 minutes without recursivity:

import os
import time

folder = 'pathname'

files = [(f, os.path.getmtime(f)) for f in os.listdir(folder) 
                if os.path.isfile(f)]

files = sorted(files, key=lambda x: x[1], reverse=True)

last_modified_file = None if len(files) == 0 else files[0][0]

# get age file in minutes from now
def age(filename):
    return (time.time() - os.path.getmtime(filename))//60

if last_modified_file is not None:
    if age(last_modified_file) >= 5:
        os.remove(last_modified_file)

Upvotes: 2

Related Questions