qwap
qwap

Reputation: 71

How can I execute a python script on all files in a directory

I have a python script that takes a path of a volume and returns the segmented volume, however it only takes one at a time:

python objectseg.py path_to_img_nifti.nii output_name.nii

Now I want to do this for all volumes in a directory. I tried something like this in python

from pathlib import Path
paths=[os.path.abspath(path) for path in Path("directory").iterdir() if str(path).endswith(".nii")]
for path in paths:
    !python objectseg.py path path

--> [Errno 2] No such file or directory: 'path'

Upvotes: 0

Views: 120

Answers (1)

tripleee
tripleee

Reputation: 189327

Probably something like this;

from pathlib import Path

from objectseg import somefunction as objsegfn


for path in Path(".").iterdir():
    if str(path).endswith(".nii")
        objsegfn(path, path)

Unless objsegfn is badly broken, there should be no need to convert the paths to absolute paths. The above simply loops over whatever files you have in your current directory; cd to Directory if that's where you want to run it.

The main work is to refactor objectseg.py into a module you can import if it's not already in that format. Briefly, if it currently looks like

print(sys.argv[1], sys.argv[2], "!")

(just to keep it really simple), refactor it to something like

def somefunction(src, dst):
    print(src, dst, "!")

if __name__ == __main__:
    import sys
    somefunction(sys.argv[1], sys.argv[2])

Probably come up with a better name than somefunction too; we have no idea what it does, so it's hard to come up with a descriptive name.

... Or if this is just a one-off, probably just run a simple shell loop. See e.g. Looping over pairs of values in bash

Upvotes: 1

Related Questions