Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find the most recent file in a directory without reading all the contents of it

Tags:

python

c

unix

I'm trying to find out the latest file in a huge filesystem. One way to do this is to go through all directories - one at a time, read its contents, select the latest file etc.

The obvious drawback is I have to get all the files in a specific directory. I was wondering whether there was a 'magic' call in Python [1] which Unix supports to get just the latest file in a directory.

[1]. My application is in Python, but if a readymade solution doesnt exist in stdlib, please provide C (lanuage) alternatives using system calls. I'm willing to write a C-extension and make this work.

Thanks

update: I suppose I should offer an explanation on why an inotify type solution wont work for me. I was simply looking for a system call using Python/C which could give me the latest file. Yes, one could have inotify (or a similar overarching setup) which monitors FS changes but given a random directory how do I find the latest file is the essence of the question.

like image 777
Jeffrey Jose Avatar asked Dec 16 '22 18:12

Jeffrey Jose


1 Answers

Have you considered using pyinotify which can watch a directory and subdirectories?
This might require your code to be threaded, say, a watcher thread that records the latest changes for the main thread to poll.

Alternatively, you could use popen and get the result of 'ls -t | head -1'

like image 79
Spaceghost Avatar answered May 16 '23 06:05

Spaceghost