Reputation: 43
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?
Upvotes: 4
Views: 1293
Reputation: 17168
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]
Upvotes: 7
Reputation: 12381
Just write your own, using the classic DSU method:
try:
# At least give it a chance, in case a modern version of Python is running,
# it would be faster
my_max = max(my_list, key=my_func)
except:
my_decorated = [(my_func(x), x) for x in my_list]
my_max = max(my_decorated)[1]
You could even do something that the top, that overrides the built-in max
function for your version, if you need to do this a lot in the code and don't want to put this in every location...
Upvotes: 1
Reputation: 121976
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]
Upvotes: 6