Skip to content Skip to sidebar Skip to footer

Identify Latest File Based On Version In Python

I have a list of .jar files in my directory: testapplication-1.0.jar testapplication-1.1.jar testapplication-2.0.jar I want to get the latest jar based on the version in the filen

Solution 1:

Define a function that parses the version number from a filename into a tuple, then use that function as the key= parameter to the max() function:

from pathlib import Path

filenames = ["testapplication-1.0.jar", "testapplication-1.1.jar", "testapplication-2.0.jar"]

def parse_version(filename):
    return tuple(int(x) for x in Path(filename).stem.split('-')[-1].split('.')) 

max(filenames, key=parse_version)  # 'testapplication-2.0.jar'

If you need something more complicated, like also getting the second-latest version, you could also use the parse_version function as the key= parameter to the sorted() function.


Solution 2:

Solution

from packaging import version

jar_files = ['testapplication-1.0.jar', 'testapplication-1.1.jar', 'testapplication-2.0.jar']

versions = [jar_file.rpartition('.')[0].split('-')[1] for jar_file in jar_files]

_version = versions[0]

for ver in versions[1:]:
    if version.parse(ver) > version.parse(_version):
        _version = ver

print(f'testapplication-{_version}.jar')

Post a Comment for "Identify Latest File Based On Version In Python"