Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python glob -- get newest file from list

I am able to retrieve the list of files with similar names. What I am trying to do is retrieve the newest file in order to be manipulated. With glob, I am able to retrieve all of the files, but not the specific one.

Here is my sample code:

permissionCurrentDate = '\n'.join(glob.iglob(os.path.join("PermissionsOnSystems*")))

Here is the result when I print it:

PermissionsOnSystems2.txt

PermissionsOnSystems20170313-144036.txt

What I want is just PermissionsOnSystems20170313-144036.txt.

How can I do this?

Thanks!

like image 226
Glitteropia Avatar asked Mar 13 '17 19:03

Glitteropia


People also ask

How can I tell when a Python file was last modified?

Python's os. path. getmtime() method can be used to determine when the given path was last modified.


1 Answers

Depending on if you want the newest file from the perspective of access time, metadata change time, or modify time you can use os.path.getatime, os.path.getctime or os.path.getmtime. So something like:

max(glob.iglob('PermissionsOnSystems*'), key=os.path.getmtime)
like image 56
Colin Avatar answered Oct 22 '22 09:10

Colin