-1

I have a list of files mapped as following:

files = os.listdir(os.getcwd())

[
'MESSAGEHUB_INGEST.log.5', 
'MESSAGEHUB_INGEST.log.2', 
'MESSAGEHUB_INGEST.log.3', 
'MESSAGEHUB_INGEST.log.4', 
'MESSAGEHUB_INGEST.log.10', 
'MESSAGEHUB_INGEST.log.1', 
'MESSAGEHUB_INGEST.log.6', 
'MESSAGEHUB_INGEST.log.7', 
'MESSAGEHUB_INGEST.log'
]

When I try to sort it with files.sort() I get this:

[
'MESSAGEHUB_INGEST.log', 
'MESSAGEHUB_INGEST.log.1', 
'MESSAGEHUB_INGEST.log.10', 
'MESSAGEHUB_INGEST.log.2', 
'MESSAGEHUB_INGEST.log.3', 
'MESSAGEHUB_INGEST.log.4', 
'MESSAGEHUB_INGEST.log.5', 
'MESSAGEHUB_INGEST.log.6', 
'MESSAGEHUB_INGEST.log.7'
]

Notice that the file MESSAGEHUB_INGEST.log.10 is in the 3rd position of the list.

How to sort this list properly so it is in correct sequence?

[
'MESSAGEHUB_INGEST.log', 
'MESSAGEHUB_INGEST.log.1', 
'MESSAGEHUB_INGEST.log.2', 
'MESSAGEHUB_INGEST.log.3', 
'MESSAGEHUB_INGEST.log.4', 
'MESSAGEHUB_INGEST.log.5', 
'MESSAGEHUB_INGEST.log.6', 
'MESSAGEHUB_INGEST.log.7',
'MESSAGEHUB_INGEST.log.10', 
]
andrefgj
  • 29
  • 5
  • Yes, it did the trick! https://stackoverflow.com/questions/4836710/does-python-have-a-built-in-function-for-string-natural-sort – andrefgj Feb 04 '19 at 11:43

1 Answers1

-1

Try this out:
Using regexp to extract the number following the word log in each entry. If re.findall returns an empty list, then return -1, so that it gets the topmost priority in the sorted list.

import re
def fun(x):
    li = re.findall(r'.log.([0-9]*)',x)
    if li:
        return int(li[0])
    else:
        return -1

print(sorted(li,key= lambda x: fun(x)))
taurus05
  • 2,491
  • 15
  • 28
  • can the user tell me, what's wrong with the approach and why was it downvoted? – taurus05 Feb 04 '19 at 03:13
  • Could you explain a little more about this snippet? I tried to apply it, but it did not work (btw, I did not downvoted it). – andrefgj Feb 04 '19 at 11:27
  • There is NameError in the code. I've corrected it now! I'm using regexp to find out the number after the word `.log.num` & using it as a key to sort the entries. If incase there is no number, an empty list is returned. All such entries will be placed on the beginning of the sorted list. – taurus05 Feb 04 '19 at 11:29