Glitteropia
Glitteropia

Reputation: 117

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!

Upvotes: 5

Views: 454

Answers (1)

Colin
Colin

Reputation: 2137

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)

Upvotes: 5

Related Questions