title: How to Naturally Sort Pathlib objects in Python?
body: <p>I am trying to create a sorted list of files in the <code>./pages</code> directory.  This is what I have so far:</p>
  
  <pre><code>import numpy as np
  from PIL import Image
  import glob
  from pathlib import Path
  
  
  # sorted( l, key=lambda a: int(a.split("-")[1]) )
  image_list = []
  
  for filename in Path('./pages').glob('*.jpg'):
  #     sorted( i, key=lambda a: int(a.split("_")[1]) )
  #     im=Image.open(filename)
      image_list.append(filename)
  
  print(*image_list, sep = "\n")
  
  </code></pre>
  
  <p>current output:</p>
  
  <pre><code>pages/page_1.jpg  
  pages/page_10.jpg  
  pages/page_11.jpg  
  pages/page_12.jpg  
  pages/page_2.jpg  
  pages/page_3.jpg  
  pages/page_4.jpg  
  pages/page_5.jpg  
  pages/page_6.jpg  
  pages/page_7.jpg  
  pages/page_8.jpg  
  pages/page_9.jpg  
  </code></pre>
  
  <p>Expected Output:  </p>
  
  <pre><code>pages/page_1.jpg   
  pages/page_2.jpg  
  pages/page_3.jpg  
  pages/page_4.jpg  
  pages/page_5.jpg  
  pages/page_6.jpg  
  pages/page_7.jpg  
  pages/page_8.jpg  
  pages/page_9.jpg  
  pages/page_10.jpg  
  pages/page_11.jpg  
  pages/page_12.jpg
  </code></pre>
  
  <p>I've tried the solutions found in the <a href="https://stackoverflow.com/questions/4836710/does-python-have-a-built-in-function-for-string-natural-sort">duplicate</a>, but they don't work because the pathlib files are class objects, and not strings.  They only appear as filenames when I print them.</p>
  
  <p>For example:</p>
  
  <pre><code>print(filename) # pages/page_1.jpg  
  print(type(filename)) # &lt;class 'pathlib.PosixPath'&gt;
  </code></pre>
  
  <p>Finally, this is working code. Thanks to all.  </p>
  
  <pre><code>from pathlib import Path
  import numpy as np
  from PIL import Image
  import natsort
  
  def merge_to_single_image():
      image_list1 = []
      image_list2 = []
      image_list3 = []
      image_list4 = []
  
      for filename in Path('./pages').glob('*.jpg'):
          image_list1.append(filename)
  
      for i in image_list1:
          image_list2.append(i.stem)
      #     print(type(i.stem))
  
      image_list3 = natsort.natsorted(image_list2, reverse=False)
  
      for i in image_list3:
          i = str(i)+ ".jpg"
          image_list4.append(Path('./pages', i))
  
      images = [Image.open(i) for i in image_list4]
      # for a vertical stacking it is simple: use vstack
      images_combined = np.vstack(images)
      images_combined = Image.fromarray(images_combined)
      images_combined.save('Single_image.jpg')
  </code></pre>