title: Combine mp4 files by order based on number from filenames in Python
body: <p>I try to merge lots of <code>mp4</code> files from a directory <code>test</code> into one <code>output.mp4</code> using <code>ffmpeg</code> in Python.</p>
  <pre><code>import os
  
  path = '/Users/x/Documents/test'
  
  for filename in os.listdir(path):
      if filename.endswith(&quot;.mp4&quot;):
          print(filename)
  </code></pre>
  <p>Output:</p>
  <pre><code>4. 04-unix,minix,Linux.mp4
  6. 05-Linux.mp4
  7. 06-ls.mp4
  5. 04-unix.mp4
  9. 08-command.mp4
  1. 01-intro.mp4
  3. 03-os.mp4
  8. 07-minux.mp4
  2. 02-os.mp4
  10. 09-help.mp4
  </code></pre>
  <p>I have tried with the solution below from the reference here: <a href="https://stackoverflow.com/questions/53230945/ffmpy-concatenate-multiple-files-with-a-file-list">ffmpy concatenate multiple files with a file list</a></p>
  <pre><code>import os
  import subprocess
  import time
  
  
  base_dir = &quot;/path/to/the/files&quot;
  video_files = &quot;video_list.txt&quot;
  output_file = &quot;output.avi&quot;
  
  # where to seek the files
  file_list = open(video_files, &quot;w&quot;)
  
  # remove prior output
  try:
      os.remove(output_file)
  except OSError:
      pass
  
  # scan for the video files
  start = time.time()
  for root, dirs, files in os.walk(base_dir):
      for video in files:
          if video.endswith(&quot;.avi&quot;):
              file_list.write(&quot;file './%s'\n&quot; % video)
  file_list.close()
  
  # merge the video files
  cmd = [&quot;ffmpeg&quot;,
         &quot;-f&quot;,
         &quot;concat&quot;,
         &quot;-safe&quot;,
         &quot;0&quot;,
         &quot;-loglevel&quot;,
         &quot;quiet&quot;,
         &quot;-i&quot;,
         &quot;%s&quot; % video_files,
         &quot;-c&quot;,
         &quot;copy&quot;,
         &quot;%s&quot; % output_file
         ]
  
  p = subprocess.Popen(cmd, stdin=subprocess.PIPE)
  
  fout = p.stdin
  fout.close()
  p.wait()
  
  print(p.returncode)
  if p.returncode != 0:
      raise subprocess.CalledProcessError(p.returncode, cmd)
  
  end = time.time()
  print(&quot;Merging the files took&quot;, end - start, &quot;seconds.&quot;)
  </code></pre>
  <p>I have merged them and get an <code>output.mp4</code> but the files are not merged in order with the first number split by point (<code>1, 2, 3, ...</code>): which I can get by <code>filename.split(&quot;.&quot;)[0]</code>:</p>
  <pre><code>1. 01-intro.mp4
  2. 02-os.mp4
  3. 03-os.mp4
  4. 04-unix,minix,Linux.mp4
  5. 04-unix.mp4
  6. 05-Linux.mp4
  7. 06-ls.mp4
  8. 07-minux.mp4
  9. 08-command.mp4
  10. 09-help.mp4
  </code></pre>
  <p>How can I merge them correctly and concisely in Python? Thanks.</p>