0

i'm using glob.glob() to get a list of files from a directory.

the result is this list. there is a way i can sort it using the int part of the filename?

['export_p-01.xml',
 'export_p-02.xml',
 'export_p-03.xml',
 'export_p-04.xml',
 'export_p-05.xml',
 'export_p-06.xml',
 'export_p-07.xml',
 'export_p-08.xml',
 'export_p-09.xml',
 'export_p-10.xml',
 'export_p-100.xml',
 'export_p-101.xml',
 'export_p-102.xml',
 'export_p-103.xml',
 'export_p-104.xml',
 'export_p-105.xml',
 'export_p-106.xml',
 'export_p-107.xml',
 'export_p-108.xml',
 'export_p-109.xml',
 'export_p-11.xml',
]
robert laing
  • 1,331
  • 2
  • 12
  • 19
  • This question was in my final exam , I couldn't solve it there either lol. –  Jan 18 '15 at 19:53
  • The duplicate is specifically asking about Python 3, but the answers cover both Python 2 and 3. – NPE Jan 18 '15 at 19:54

1 Answers1

1

Here you go, with a custom lambda for using as key:

In [1]: l = ['export_p-01.xml', ...]

In [2]: sorted(l, key = lambda x: int(x.split(".")[0].split("-")[-1]))
Out[2]: 
['export_p-01.xml',
 'export_p-02.xml',
 'export_p-03.xml',
 'export_p-04.xml',
 'export_p-05.xml',
 'export_p-06.xml',
 'export_p-07.xml',
 'export_p-08.xml',
 'export_p-09.xml',
 'export_p-10.xml',
 'export_p-11.xml',
 'export_p-100.xml',
 'export_p-101.xml',
 'export_p-102.xml',
 'export_p-103.xml',
 'export_p-104.xml',
 'export_p-105.xml',
 'export_p-106.xml',
 'export_p-107.xml',
 'export_p-108.xml',
 'export_p-109.xml']
Anshul Goyal
  • 73,278
  • 37
  • 149
  • 186