Search code examples
pythoncommandcall

apply command to list of files in python


I've a tricky problem. I need to apply a specific command called xRITDecompress to a list of files with extension -C_ and I should do this with Python.

Unfortunately, this command doesn't work with wildcards and I can't do something like:

os.system("xRITDecompress *-C_")

In principle, I could write an auxiliary bash script with a for cycle and call it inside my python program. However, I'd like not to rely on auxiliary files...

What would be the best way to do this within a python program?


Solution

  • You can use glob.glob() to get the list of files on which you want to run the command and then for each file in that list, run the command -

    import glob
    for f in glob.glob('*-C_'):
        os.system('xRITDecompress {}'.format(f))
    

    From documentation -

    The glob module finds all the pathnames matching a specified pattern according to the rules used by the Unix shell.

    If by _ (underscore) , you wanted to match a single character , you should use - ? instead , like -

    glob.glob('*-C?')
    

    Please note, glob would only search in current directory but according to what you wanted with the original trial, seems like that maybe what you want.


    You may also, want to look at subprocess module, it is a more powerful module for running commands (spawning processes). Example -

    import subprocess
    import glob
    for f in glob.glob('*-C_'):
        subprocess.call(['xRITDecompress',f])