I\'m writing a Python script where part of its function is to find the last modified file of a specific kind. In my case, it\'s for the last modified screen saver plist file on
listdir
won't prepend the directory name, so you cannot pass os.path.getmtime
as-is.
Wrap it with a lambda and join with the source directory:
MacPlistFile = max((f for f in os.listdir(MacPlistPath) if f.lower().endswith('.plist') and f.lower().startswith('com.apple.screensaver.')), key=lambda f : os.path.getmtime(os.path.join(MacPlistPath,f)))
But looking at the bigger picture, you'd be even better off with glob.glob
and a wildcard:
import glob
MacPlistFile = os.path.basename(max(glob.glob(os.path.join(MacPlistPath,"com.apple.screensaver.*.plist")), key=os.path.getmtime))
glob.glob
returns the full path, so now you can use os.path.getmtime
directly as a key. You just have to perform an os.path.basename
in the end to get only the last modified file name.
Aside: no need to create a list comprehension. A generator comprehension is enough for max
to work efficiently.