How to get the latest file

I am new to Python and I need to write code that contains a directory containing files with random names, for example:

JuniperAccessLog-stand-alone-FCL_VPN-20120319-1110.gz
JuniperAccessLog-stand-alone-FCL_VPN-20120321-1110.gz

I need to get a more recent file

I try this, but to no avail.

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 

is it possible to use this logic?

+4
source share
4 answers

If you need the latest file, you can take advantage of the fact that they seem to be sorted by date:

 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],) 
+8
source

You can get what you want using the glob :

 def GetLatestArchive(): "Return the most recent JuniperAccessLog file for today date." import glob from datetime import datetime archive_format = datetime.now().strftime("JuniperAccessLog-standalone-FCL_VPN-%Y%m%d-%H*.gz") archives = glob.glob(archive_format) if len(archives) > 0: # The files should come sorted, return the last one in the list. return archives[-1] else: # No files were matched return None 
+2
source

glob will do what you are trying to do with its popup call.

 import os import glob from datetime import datetime t = datetime.now() archive = t.strftime("JuniperAccessLog-standalone-FCL_VPN-%Y%m%d-%H*.gz") files = glob.glob(archive) for f in files: # do something with f 
0
source
  • Define a function to parse the date from the file name:

     def date_from_path(path): m = re.match(r"JuniperAccessLog-standalone-FCL_VPN-(\d+)-(\d+).\gz", path) return int(m.group(1)), int(m.group(2)) 

    This function takes advantage of the fact that your date and time values ​​are represented as integers.

  • Use max to get the last file:

     max(os.listdir(directory), key=date_from_path) 
0
source

Source: https://habr.com/ru/post/1402445/


All Articles