title: Sort filenames in directory in ascending order
body: <p>I have a directory with jpgs and other files in it, the jpgs all have filenames with numbers in them. Some may have additional strings in the filename.</p>
  
  <p>For example.</p>
  
  <pre><code>01.jpg
  </code></pre>
  
  <p>Or it could be</p>
  
  <pre><code>Picture 03.jpg
  </code></pre>
  
  <p>In Python I need a list of all the jpgs in ascending order.
  Here is the code snippet for this</p>
  
  <pre><code>import os
  import numpy as np
  
  myimages = [] #list of image filenames
  dirFiles = os.listdir('.') #list of directory files
  dirFiles.sort() #good initial sort but doesnt sort numerically very well
  sorted(dirFiles) #sort numerically in ascending order
  
  for files in dirFiles: #filter out all non jpgs
      if '.jpg' in files:
          myimages.append(files)
  print len(myimages)
  print myimages
  </code></pre>
  
  <p>What I get is this</p>
  
  <pre><code>['0.jpg', '1.jpg', '10.jpg', '11.jpg', '12.jpg', '13.jpg', '14.jpg',
   '15.jpg', '16.jpg', '17.jpg', '18.jpg', '19.jpg', '2.jpg', '20.jpg',
   '21.jpg', '22.jpg', '23.jpg', '24.jpg', '25.jpg', '26.jpg', '27.jpg',
   '28.jpg', '29.jpg', '3.jpg', '30.jpg', '31.jpg', '32.jpg', '33.jpg',
   '34.jpg', '35.jpg', '36.jpg', '37.jpg', '4.jpg', '5.jpg', '6.jpg',
   '7.jpg', '8.jpg', '9.jpg']
  </code></pre>
  
  <p>Clearly it sorts blindly the most significant number first. I tried using <code>sorted()</code> as you can see hoping that it would fix it but it makes no difference.</p>