How to "naturally sort" files that end with a number (png0 to png188) via Python's natsort?

152 Views Asked by At

I have a folder that has plots in PNGs like earthquake0, earthquake1, earthquake2, and so on. These photos are converted to GIF via moviepy but Python's sorting results to 1, 10, 100 instead of 1, 2, 3.

Here's the moviepy code

import os
os.chdir(r'path')
from moviepy.editor import *

image_list = 'exports' # folder 
my_clip = ImageSequenceClip(image_list, fps=0.75)
my_clip.write_gif('eqph_gif.gif')

I have tried adding this but Python says it can't find the folder

image_list = natsort.natsorted(image_list)
1

There are 1 best solutions below

0
BallpenMan On

Solved it!

def gif():
    os.chdir(r'C:\Users\imper\Documents\new_GISfiles\earthquakesPH\exports')
    imgs = humansorted(os.listdir('.'))
    my_clip = ImageSequenceClip(imgs, fps=1.5)
    my_clip.write_videofile('eqph.mp4', fps=15)

Someone from r/learnpython pointed out that I can't just write imgs = 'exports' even if I already set up the working directory os.chdir(r'path'). https://www.reddit.com/r/learnpython/comments/guabw3/the_humansorted_function_work_when_ran_in_the/