Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the most recent file

Tags:

python

file

i am newbie in Python language and i need write a code that list directory that contains files with random names, for example:

JuniperAccessLog-standalone-FCL_VPN-20120319-1110.gz
JuniperAccessLog-standalone-FCL_VPN-20120321-1110.gz

I need get the more recent file

I try this, but without success.

import os
from datetime import datetime 

t = datetime.now()
archive = t.strftime("JuniperAccessLog-standalone-FCL_VPN-%Y%m%d-%H*.gz")
file = os.popen(archive)

Result:

sh: JuniperAccessLog-standalone-FCL_VPN-20120320-10*.gz: command not found

have a possibility the use this logic ?

like image 698
Mario Uzae Avatar asked Mar 20 '12 13:03

Mario Uzae


People also ask

How do I find the last file in Linux?

Finding last day modified files in Linux:The find command is used to search files. The newermt command compares files timestamp with the argument passed, in this case “1 day ago”. Then, the ls command is passed to list the files. To find last day modified files, you can also use the mtime command together with find.

How do I find recently modified files in Linux?

-mtime n is an expression that finds the files and directories that have been modified exactly n days ago. In addition, the expression can be used in two other ways: -mtime +n = finds the files and directories modified more than n days ago. -mtime -n = finds the files and directories modified less than n days ago.


1 Answers

If you want the most recent file, you could take advantage of the fact that they appear to sort into date time order:

import os

logdir='.' # path to your log directory

logfiles = sorted([ f for f in os.listdir(logdir) if f.startswith('JuniperAccessLog-standalone-FCL_VPN')])

print "Most recent file = %s" % (logfiles[-1],)
like image 176
MattH Avatar answered Nov 03 '22 05:11

MattH