0

I have a directory containing a lot of textfiles named in a specific order:

0.txt
1.txt
2.txt
....
100.txt
101.txt
.....
40000.txt

When im trying to retrieve a sorted list of all the files im using:

for file in sorted(os.listdir(filepath)):
            print(file)

and the result im getting is:

0.txt
1.txt
10.txt
100.txt
1000.txt
10000.txt
10001.txt
10002.txt
10003.txt
10004.txt
.....

Which is not how i want it, i want it in normal ascending order:

0.txt
1.txt
2.txt
3.txt
4.txt
...

Does anyone know how to do this?

StevePick
  • 1
  • 1
  • 1
  • 1
  • 1
    If your strings are exactly this format, you can just `os.path.splitext` to take off the `.txt`, then `int()` the basename, and that’s your sort key. – abarnert May 31 '18 at 17:48
  • 3
    [natsort](https://github.com/SethMMorton/natsort) performs natural sorting which is what you need. – Austin May 31 '18 at 17:50

2 Answers2

9

Could use a lambda expression

import os

filelist = os.listdir(path)
filelist = sorted(filelist,key=lambda x: int(os.path.splitext(x)[0]))

for file in filelist:
    print(file)

Outputs as:

1.txt
2.txt
3.txt
4.txt
5.txt
6.txt
7.txt
8.txt
9.txt
10.txt
Tom
  • 685
  • 8
  • 17
3

You can replace the ".txt" and then convert the value to int and sort.

Ex:

for file in sorted(os.listdir(filepath), key=lambda x: int(x.replace(".txt", ""))):
    print(file)
Rakesh
  • 81,458
  • 17
  • 76
  • 113