问题描述
做
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、 ...
解决方法
为了扩展我的评论,也许这样的事情会做。这会提取在小数点之间或文件末尾找到的第一个数字序列,并使用该值作为主排序键,并使用完整的文件名作为辅助。
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')
,
基于 Is there a built in function for string natural sort?,这是一个单行解决方案:
{{1}}