I want to use the cdo command for masking the .nc file (the command below):

cdo div input.nc maskfile.nc outputfile.nc

The command above should be applied over multiple .nc files (looping) in python, can anyone assist in how to apply it?

Also the same case with weighted mean command from cdo,

cdo fldmean input.nc fldmean.nc

1 Answer 1


I have very little information of what exactly you're trying to do, so I'm going to make a lot of guesses. Here's a quick and dirty way to get it done:

import subprocess

input_list  = ['input_1.nc','input_2.nc','input_3.nc']
mask_list   = ['mask_1.nc','mask_2.nc','mask_3.nc']
output_list = ['output_1.nc','output_2.nc','output_3.nc']

for i in range(len(input_list)):
    this_input  = input_list[i]
    this_mask   = mask_list[i]
    this_output = output_list[i]
    subprocess_str = f'cdo div {this_input} {this_mask} {this_output}'

I'm assuming you want to run the cdo command from your terminal.

Also, you'll have to fill out the lists above with the files you want to use in order.

You can use a very similar structure to solve your second problem too. I hope this helps!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.