首页 > 解决方案 > 如何对包含数字的 glob.glob 进行排序?

问题描述

正在做

glob.glob('/var/log/apache2/other_vhosts_access.log*')

给出一个未排序的列表,例如['....76.gz', '....16.gz', '....46.gz', ...]. 还,

sorted(glob.glob('/var/log/apache2/other_vhosts_access.log*')) 

other_vhosts_access.log
other_vhosts_access.log.1
other_vhosts_access.log.10.gz
other_vhosts_access.log.11.gz
other_vhosts_access.log.12.gz
...
other_vhosts_access.log.19.gz
other_vhosts_access.log.2.gz

如何有更好的排序? .log, .log.1, .log.2.gz, ..., .log.9.gz, .log.10.gz, ...

标签: pythonsortingglobnatural-sort

解决方案


为了扩展我的评论,也许这样的事情会做。这会提取在小数点之间或文件末尾找到的第一个数字序列,并将该值用作主排序键,并将完整文件名用作辅助键。

file_list = """
other_vhosts_access.log
other_vhosts_access.log.1
other_vhosts_access.log.10.gz
other_vhosts_access.log.11.gz
other_vhosts_access.log.12.gz
other_vhosts_access.log.19.gz
other_vhosts_access.log.2.gz
""".strip().split()

import re

re_num = r"\.(\d+)(\.|$)"

def sort_key(file_name):
    match=re.search(re_num,file_name)
    if match is None:
        return(0,file_name)
    else:
        return(int(match.group(1)),file_name)
    
print(*sorted(file_list,key=sort_key),sep='\n')

推荐阅读