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

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


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

Then you loop over the filenames. Like so:

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

If you prefer subprocess, use subprocess. :-)


Use os.walk to iterate recursively over directory content:

import osroot_dir = '.'for directory, subdirectories, files in os.walk(root_dir):    for file in files:        print os.path.join(directory, file)

No real difference between os.system and subprocess.call here - unless you have to deal with strangely named files (filenames including spaces, quotation marks and so on). If this is the case, subprocess.call is definitely better, because you don't need to do any shell-quoting on file names. os.system is better when you need to accept any valid shell command, e.g. received from user in the configuration file.


Python might be overkill for this.

for file in *; do mencoder -some options $file; rm -f $file ; done