14
Aug

Python Script to Recursively Search For and Generate Thumbnails for Video Files

This script will recursively search for files based on listed extension names and then use the ‘ffmpegthumbnailer’ program to generate a thumbnail for each file it finds.

If you’re on a Ubuntu system, you should be able to install ffmpegthumbnailer using apt-get install ffmpegthumbnailer.

#!/usr/bin/python

import os

for root, dirnames, filenames in os.walk('/var/www/media/'):
  for filename in filenames:
    if filename.lower().endswith(('.m4v', '.mov', '.mpeg', 'mp4')): 
      ifile = os.path.join(root, filename)
      ofile = os.path.splitext(ifile)[0] + ".jpg"
      try:
        with open(ofile) as f: pass
      except IOError as e:
        print "Generating thumbnail for: " + ifile

        fftoptions = "-s0 -f"
        command = "ffmpegthumbnailer -i %s -o %s %s" % (ifile, ofile, fftoptions)

        p = os.popen(command,"r")
        while 1:
          line = p.readline()
          if not line: break
          print line

I had a specific purpose for this script, but you could easily modify it to fit your needs. When you save the file, don’t forget to mark it as executable with chmod +x scriptname.py.

Feel free to donate if this post prevented any headaches! Another way to show your appreciation is to take a gander at these relative ads that you may be interested in:


There's 5 Comments So Far

  • zon
    August 16th, 2012 at 8:36 am

    How do you get your code to display via colors?

  • [email protected]
    August 16th, 2012 at 8:43 am

    It’s a plugin called “Syntax Highlighter for WordPress”. Then, I just surround my code in the language I want to use like [PYTHON], [CPP], [BASH], etc…

  • KisssKoool
    December 14th, 2012 at 6:04 pm

    Thanks man !
    You saved my night !

  • Jan
    June 19th, 2013 at 5:02 am

    Hi,

    I am a Paython novice, but stumbled upon one thing: you may want to add some apostrophes so that directory names with blanks are supported:

    command = “ffmpegthumbnailer -i ‘%s’ -o ‘%s’ ‘%s'” % (ifile, ofile, fftoptions)

  • vittorio
    January 15th, 2015 at 2:27 am

    Hi!
    I get a

    File “/home/evo/ffmpegthumbnailer.py”, line 13
    print “Generating thumbnail for: ” + ifile
    ^
    SyntaxError: Missing parentheses in call to ‘print’

Share your thoughts, leave a comment!