0

I have a directory with these .txt files:

1.txt
2.txt
3.txt
...
100.txt
138.txt
...
100.txt
1923.txt

If I list the directory with python (usign glob or os.listdir()), it produces such result:

adaptedUsers = sorted(glob.glob(dirName + '*.txt'))

1.txt
10.txt
1000.txt
..
2.txt
..

However I want to list the files in sorted with their numeric value as in windows directory files listing. How can I do this without renaming the files?

eaytan
  • 319
  • 2
  • 3
  • 10

1 Answers1

0

yes. Use split and sort with a key.

def natural_sort(x):
   radix = x.split(".")[0]
   return int(radix) if radix.isdigit() else 0

sorted_list = sorted(os.listdir("."),key = natural_sort)

handles the case where there are non-numeric files in the directory.

(I had written this answer before the duplicate came out, so tagging it as community wiki but leaving it because it solves OP question, when the duplicate link needs to be adapted)

Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219