1

I am fetching all list of file names from a directory But when i sort it is not sorted according to the number wise file names in final.txt file

My Python code :

pth=r'/d/demo'
fname=glob.glob(pth+"/['ABC']*.txt")
nlist='/d/bk/final.txt'

fname.sort()

for i in fname:
    file=os.path.basename(i)
    nlist.write(file+os.linesep)

The above code output coming in below format in final.txt file

ABC1.txt
ABC11.txt
ABC10.txt
ABC2.txt
ABC3.txt
ABC4.txt
ABC5.txt
ABC6.txt
ABC7.txt
ABC8.txt
ABC9.txt
ABC13.txt
ABC12.txt

Expected output in below format :

ABC1.txt
ABC2.txt
ABC3.txt
ABC4.txt
ABC5.txt
ABC6.txt
ABC7.txt
ABC8.txt
ABC9.txt
ABC10.txt
ABC11.txt
ABC12.txt
ABC13.txt
codeholic24
  • 955
  • 4
  • 22

1 Answers1

0

What you want is named natural sort order. If using external modules is ok in your case then you might harness natsort (which might be installing simply by pip install natsort) following way:

import natsort
fname = ["ABC1.txt","ABC11.txt","ABC10.txt","ABC2.txt","ABC3.txt"]
fname = natsort.natsorted(fname)
print(fname)

output

['ABC1.txt', 'ABC2.txt', 'ABC3.txt', 'ABC10.txt', 'ABC11.txt']

Note that natsort.natsorted is supposed to be used like sorted rather than .sort, i.e. it does return new list.

Daweo
  • 31,313
  • 3
  • 12
  • 25