1

glob.glob(file_naming)

Doing this gives me two files:

['/srv/tmp/what/123_aaa_bbb_20190110043711.XML',
 '/srv/tmp/what/234_xxx_yyy_20190110043710.XML']

How can I sort them in order of the last part( 20190110043711)? I need a result like:

['/srv/tmp/what/123_aaa_bbb_20190110043710.XML',
 '/srv/tmp/what/234_xxx_yyy_20190110043711.XML']
Ashu
  • 37
  • 1
  • 1
  • 9

2 Answers2

5

Use sorted:

>>> sorted(l,key=lambda x: int(x.split('_')[-1]))
['/srv/tmp/what/234_xxx_yyy_20190110043710.XML', '/srv/tmp/what/123_aaa_bbb_20190110043711.XML']
>>> 
U13-Forward
  • 69,221
  • 14
  • 89
  • 114
  • after using this, it is still not in order: `/srv/tmp/tmporxECk/T052_UK_20190118113012.XML /srv/tmp/tmporxECk/T681_UK_20190110043710.XML /srv/tmp/tmporxECk/T685A_UK_20190118113012.XML /srv/tmp/tmporxECk/T683S_UK_20190118113012.XML /srv/tmp/tmporxECk/T682I_UK_20190118113012.XML /srv/tmp/tmporxECk/T009B_UK_20190110043710.XML` This is the order that I am getting. The last part is the date and time stamp and I want to sort according to that @U9-Forward – Ashu Feb 22 '19 at 12:38
0

Does Python have a built in function for string natural sort? you can see this post for natural sorting.

you can use https://pypi.org/project/natsort/ -- natsort pasted an example below

 a = ['Apple', 'apple15', 'Banana', 'apple14,689', 'banana']
 natsorted(a, alg=ns.REAL | ns.LOCALE | ns.IGNORECASE)
user_D_A__
  • 460
  • 2
  • 6
  • 14