如何按编号对linux中的文件进行排序?

时间:2015-07-07 22:09:24

标签: python linux

我的程序读入从文件名解析的数字。我想要它的确切排序,但是,在这个例子中,列表为500,4000,7000。我的命名约定应该如何实现呢?也就是说,当我增加数字时,它会从最小到最高列出它。

我真正想要的是它按排名排序(这里从零开始),然后按递增数字排序.. 500,5000,7000。

enter image description here

期望的输出

LOG-rank-0-die-10-delay-500.txt
LOG-rank-0-die-10-delay-4000.txt
LOG-rank-0-die-10-delay-7000.txt
LOG-rank-1-die-10-delay-500.txt
LOG-rank-1-die-10-delay-4000.txt
LOG-rank-1-die-10-delay-7000.txt
LOG-rank-2-die-10-delay-500.txt
LOG-rank-2-die-10-delay-4000.txt
LOG-rank-2-die-10-delay-7000.txt

相关代码

for filenamelogs in sorted(os.listdir(log_directory)):
            for each_line in filenamelogs:
                   #various file parsing activity

我将逐个文件的数据附加到各种数组。不幸的是,如果我无法按照请求的顺序对文件进行排序,这对我来说太可怕了。也许我的问题转向开发一种自定义方法来读取我提供的排序约束下的文件。

1 个答案:

答案 0 :(得分:5)

来自对blog中链接的博客的评论:

>>> import re
>>> def sort_nicely(l):
...     """
...     Sort the given list in the way that humans expect. Modifies the original list.
...     """
...     convert = lambda text: int(text) if text.isdigit() else text
...     alphanum_key = lambda key: [convert(c) for c in re.split('([0-9]+)', key)]
...     l.sort(key=alphanum_key)
...
>>> mylist = ['LOG-rank-0-die-10-delay-500.txt',
... 'LOG-rank-0-die-10-delay-4000.txt',
... 'LOG-rank-0-die-10-delay-7000.txt',
... 'LOG-rank-1-die-10-delay-500.txt',
... 'LOG-rank-1-die-10-delay-4000.txt',
... 'LOG-rank-1-die-10-delay-7000.txt',
... 'LOG-rank-2-die-10-delay-500.txt',
... 'LOG-rank-2-die-10-delay-4000.txt',
... 'LOG-rank-2-die-10-delay-7000.txt']
>>> sort_nicely(mylist)
>>> print(*mylist, sep='\n')
LOG-rank-0-die-10-delay-500.txt
LOG-rank-0-die-10-delay-4000.txt
LOG-rank-0-die-10-delay-7000.txt
LOG-rank-1-die-10-delay-500.txt
LOG-rank-1-die-10-delay-4000.txt
LOG-rank-1-die-10-delay-7000.txt
LOG-rank-2-die-10-delay-500.txt
LOG-rank-2-die-10-delay-4000.txt
LOG-rank-2-die-10-delay-7000.txt

return新的已排序的list,而不是修改原来的{<1}}:

>>> def sort_nicely(l):
...     """
...     Sort the given list in the way that humans expect. Returns a new list.
...     """
...     convert = lambda text: int(text) if text.isdigit() else text
...     alphanum_key = lambda key: [convert(c) for c in re.split('([0-9]+)', key)]
...     return sorted(l, key=alphanum_key)
...
>>> newlist = sort_nicely(mylist)
>>> print(*newlist, sep='\n')