Using Python to execute a command on every file in a folder

Manu picture Manu · Jul 13, 2009 · Viewed 161.5k times · Source

I'm trying to create a Python script that would :

  1. Look into the folder "/input"
  2. For each video in that folder, run a mencoder command (to transcode them to something playable on my phone)
  3. Once mencoder has finished his run, delete the original video.

That doesn't seem too hard, but I suck at python :)

Any ideas on what the script should look like ?

Bonus question : Should I use

os.system

or

subprocess.call

?

Subprocess.call seems to allow for a more readable script, since I can write the command like this :

cmdLine = ['mencoder', sourceVideo, '-ovc', 'copy', '-oac', 'copy', '-ss', '00:02:54', '-endpos', '00:00:54', '-o', destinationVideo]

EDIT : Ok, that works :

import os, subprocess

bitrate = '100'
mencoder = 'C:\\Program Files\\_utilitaires\\MPlayer-1.0rc2\\mencoder.exe'
inputdir = 'C:\\Documents and Settings\\Administrator\\Desktop\\input'
outputdir = 'C:\\Documents and Settings\\Administrator\\Desktop\\output'

for fichier in os.listdir(inputdir):
    print 'fichier :' + fichier
    sourceVideo = inputdir + '\\' + fichier
    destinationVideo = outputdir + '\\' + fichier[:-4] + ".mp4"

    commande = [mencoder,
               '-of',
               'lavf',
               [...]
               '-mc',
               '0',

               sourceVideo,
               '-o',
               destinationVideo]

    subprocess.call(commande)

os.remove(sourceVideo)
raw_input('Press Enter to exit')

I've removed the mencoder command, for clarity and because I'm still working on it.

Thanks to everyone for your input.

Answer

Lennart Regebro picture Lennart Regebro · Jul 13, 2009

To find all the filenames use os.listdir().

Then you loop over the filenames. Like so:

import os
for filename in os.listdir('dirname'):
     callthecommandhere(blablahbla, filename, foo)

If you prefer subprocess, use subprocess. :-)