0

I am trying to list windows file names in sequential order but for some reason, python is displaying the file names in the following order. The 100's are displayed before the lower numbers.

Code:

import os

os.chdir('I:\SEGY\C37572')

for g in os.listdir():
    print(g)

Output:

C37572_0001.segd
C37572_00010.segd
C37572_000100.segd
C37572_000101.segd
C37572_0002.segd
C37572_0003.segd
C37572_0004.segd
C37572_0005.segd
C37572_0006.segd
C37572_0007.segd
C37572_0008.segd
C37572_0009.segd
Emi OB
  • 2,814
  • 3
  • 13
  • 29
Ebrahiem
  • 11
  • 2
  • Welcome to Stack Overflow. Please read [the help pages](http://stackoverflow.com/help), take the SO [tour], read [ask], as well as [this question checklist](https://codeblog.jonskeet.uk/2012/11/24/stack-overflow-question-checklist/). Lastly please read [the editing and formatting help](https://stackoverflow.com/editing-help) and [edit] your question to format the code and output properly. – Some programmer dude Dec 01 '21 at 07:34
  • see possible duplicate: https://stackoverflow.com/a/16090640/541038 – Joran Beasley Dec 01 '21 at 07:36

1 Answers1

0

Hello geoscientist :) It's possible to either sorted function or list.sort() list's method:

It will look like:

import os

os.chdir('I:\SEGY\C37572')
list_of_files = os.listdir(whatever_directory)
sorted_list = list_of_files.sort()

or

sorted(os.listdir(whatever_directory))

Another possibility is to use natsort library. It would be useful in the case if file names are starting with numeric symbols:

import os
from natsort import natsorted
    
os.chdir('I:\SEGY\C37572')
list_of_files = os.listdir(whatever_directory)
sorted_list = natsorted(list_of_files , key=lambda filename: y.lower())
Alex
  • 798
  • 1
  • 8
  • 21