Damn you sort function! I spent a good two days trying to establish how to list a mixed alphanumeric name into NUMERIC rather than ALPHABETICAL order. The best I was getting (with filenames like "pcap-date-1") was them listed in order 1,11,2,3,33. Which makes no sense at all. Surprisingly this appears to be non-trivial. It was also thrown off by the fact that the first pcap doesnt have a number, just an empty placeholder to signify 0.
I tried multiple approaches to this and there didn't seem to be a clear solution out there so I ended up writing my own, heavily based on various source from my good friend the internet of course.
<><><>
def list_numeric(delimiter, path):
import os
temp_list=[]
final_list=[]
for i in os.listdir(path):
y=i.split(delimiter)
if y[-1:] == ['']:
y.pop()
y.append('0')
temp_list.append((i,y[-1:]))
for i in range(len(temp_list)):
final_list.append(i)
for i,j in temp_list:
final_list[int(j[0])] = i
return final_list
<><><>
It works by splitting the file name by the delimiter ("-" in this case) and taking the final section of the split as the numeric sort term. The "if y[-1:]" section is there so that the missing 0 is added for the file which is at the very start but not numerically marked. This is then added into a list of tuples, associating each file with it's numeric sort term in each element of a temporary list.
Now based on the length of this list another empty list is created. As a result we have an element free for each of the files to be slotted into, in order, based on their numeric sort value. Once all the files have been slotted into their correct positions in "final_list", the list is returned. Et voila!
No comments:
Post a Comment