-4

I have some files and I want to process them. The file names are like this: 14K.txt, 50K.txt, 100K.txt etc. I am opening them in this way

import os
path='/blabla/my_laptop/'
filelist = os.listdir(path)
for i in sorted (filelist):
...

The problem is the files are opening in this way: 100K.txt, 19K.txt, 50K.txt. But I want to open them like this: 19K.txt, 50K.txt, 100K.txt. Can anyone please help me how to do this?

solarc
  • 5,638
  • 2
  • 40
  • 51
  • You can try sorting using the [natsort](https://github.com/SethMMorton/natsort) module – solarc Mar 05 '18 at 17:54
  • You'll need to extract the leading number, convert to int, and sort with that value as the sort key. – Prune Mar 05 '18 at 17:55
  • 1
    Thanks for your reply. I installed natsort module using pip install natsort even though it's giving moduleNotFoundError: No module named natsort – Shubhadip Chakraborty Mar 05 '18 at 18:11

1 Answers1

1
In[6]: a = ['100K.txt', '19K.txt', '50K.txt']
In[7]: sorted(a, key=lambda elem: int(elem.split('K')[0]))
Out[7]: ['19K.txt', '50K.txt', '100K.txt']
G_M
  • 3,342
  • 1
  • 9
  • 23