从文件列表中查找最大版本

2024-06-06 08:50:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要一些关于我的Linux系统的python编码帮助。在

我正在尝试整理一个大约有30个文件的目录。大多数文件是重复的,但每次开发新代码时都会递增。我需要为每组文件选择最高版本。在

我需要从下面显示的文件列表中获取AzMesa、AzChandler和AzPhoenix的最高版本。版本号总是在第二个“-”后面,并且在句点“”之前。这种格式不会改变,尽管有时城市会改变,但它总是以Az开头,总是以rpm结尾,有时“13.13”会随着代码的发布而增加。在

AzMesa-13.13-1.x86_64.rpm
AzMesa-13.13-2.x86_64.rpm
AzMesa-13.13-3.x86_64.rpm
AzChander-13.13-1.x86_64.rpm
AzChander-13.13-2.x86_64.rpm
AzPhoenix-13.13-1.x86_64.rpm
AzPhoenix-13.13-2.x86_64.rpm
AzPhoenix-13.13-3.x86_64.rpm
AzPhoenix-13.13-4.x86_64.rpm
AzPhoenix-13.13-5.x86_64.rpm

下面的代码捕获以“Az”开头、以“rpm”结尾的所有文件。然后它打印出包名,也打印出版本。在

^{pr2}$

我需要一种方法,从具有最高版本号的每个组中只捕获一个文件并将输出发送到一个文件。在

任何帮助都将不胜感激。我并不自称是python开发人员,只是尽我所能。在


Tags: 文件代码版本编码linux系统版本号结尾
1条回答
网友
1楼 · 发布于 2024-06-06 08:50:00

您可以使用python结构dict,它保存键值对,并将版本转换为int的元组,这样它就具有可比性。在

newest = dict()

for name in glob.glob('Az*.rpm'):
    #don't throw away the 13.13 - make one version
    package, combined_big_version, combined_version = name.split("-")

    #split the big vesrion into parts
    big1, big2 = combined_big_version.split(".")
    small_version, trash, trash2 = combined_version.split(".")

    #convert into a tuple of ints so we can compare them (biggest version first)
    #for example (13, 13, 1) < (13, 13, 2)
    #but         (13, 14, 1) > (13, 13, 4000)

    version = (int(big1), int(big2), int(small_version))


    #add to dictionary, or update if newer
    #store tuple (version, name) so we can get the name back 
    if not package in newest: 
        newest[package] = (version, name)
    else:
        newest[package] = max (newest[package], (version, name))

然后您可以:

^{pr2}$

相关问题 更多 >