I have a script that I wrote on a machine running Python 2.7.3 that utilizes the max function with a key along with glob to find the youngest file of a specific type in a directory. I tried to move this onto another machine only to discover that it's running Python 2.4.3 and the script doesn't work as a result.
The problem arises with the following line:
newest = max(glob.iglob(bDir + '*.[Dd][Mm][Pp]'), key=os.path.getctime)
I've looked up the documentation and can see that both iglob and max with a key aren't available until Python 2.5 >
I can change the iglob reference to just glob and get rid of the case insensitivity which works fine. But I'm not sure how to rewrite the above without using max along with a key?
I'm not certain what tools Python 2.4 has access to, but I'm pretty sure you still have list comprehensions, so you could tuple your list together with the key you want to use, compare, and then unpack. This works because tuples compare element-wise, so if you put the "key" at the front of your tuples, it'll act as the primary comparator.
# Note: untested
times_files = [(os.path.getctime(f),f) for f in glob.glob(bDir+'*.[Dd][Mm][Pp]')]
newest = max(timed_files)[1] # grab the filename back out of the "max" tuple
Alternately (and likely faster, if it matters for your use case), as @jonrsharpe pointed out, the sorted
function does allow a key
argument, so you could also sort your list and grab the last item:
newest = sorted(glob.glob(bDir + '*.[Dd][Mm][Pp]'), key=os.path.getctime)[-1]
In Python 2.4.x, sorted
does take a key
; you can apply this to your glob
and take the last item, for example:
newest = sorted(glob.glob(bDir + '*.[Dd][Mm][Pp]'), key=os.path.getctime)[-1]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With