Sort filenames in directory in ascending order with overlapping names

Viewed 25

I have been assigned to scramble some videos in pythong. So far the process involves loading in the original .mp4 file, getting each individual frame and manipulating a certain amount of those frames. The problem now I am having is ordering the frames so the individual .jpgs can be compiled back into a .mp4. Essentially, I have a folder with the following:

frame0.jpg

frame0_scrambled.jpg

frame1.jpg

frame1_scrambled.jpg

frame2.jpg

frame2_scrambled.jpg

frame3.jpg

frame3_scrambled.jpg

frame4.jpg

frame4_scrambled.jpg

And what I need is

frame0_scrambled.jpg

frame1_scrambled.jpg

frame2_scrambled.jpg

frame3_scrambled.jpg

frame4_scrambled.jpg

frame0.jpg

frame1.jpg

frame2.jpg

frame3.jpg

frame4.jpg

1 Answers

You should be able to use sorted with a custom key, something like

>>> sorted(files, key = lambda i : ('scrambled' not in i, i))
[
  'frame0_scrambled.jpg',
  'frame1_scrambled.jpg',
  'frame2_scrambled.jpg',
  'frame3_scrambled.jpg',
  'frame4_scrambled.jpg',
  'frame0.jpg',
  'frame1.jpg',
  'frame2.jpg',
  'frame3.jpg',
  'frame4.jpg'
]
Related