I want to convert a netCDF4 dataset (including grouped datasets) to Arc/Info ASCII Grids, using Python's gdal package. I tried to orientate at this question, the only thing I added is a loop over the subdatasets. Now, however, something went wrong and the script doesn't produce any output.

Can anyone help? Here's my code:

#Open existing dataset
src_ds_list = glob("..\\*.nc")

for path in src_ds_list:
    src_ds = gdal.Open(path)
    subdata = src_ds.GetSubDatasets()

    for s in range(len(subdata)):
        sds = gdal.Open(subdata[s][0])

        dst_path = '..\\' + subdata[s][0] + 'arbitrary' + '.asc'

        # Open output format driver, see gdal_translate --formats for list
        oformat = "AAIGrid"
        driver = gdal.GetDriverByName(oformat)
        # Output to new format
        dst_ds = driver.CreateCopy(dst_path, sds, 0)
        dst_ds = None
        sds= None
    src_ds = None
  • Does it work when not looping? Oct 5, 2016 at 12:17
  • No, because it cannot write multiple datasets into one ASCII Grid - or what do you mean by this comment?
    – countryman
    Oct 5, 2016 at 12:23
  • No I meant unrolling the loop. Does it work if you just try to write the first subdata set? Oct 6, 2016 at 11:07
  • Unfortunately not...does this give any hint?
    – countryman
    Oct 7, 2016 at 9:04
  • Go step by step then, maybe interactively in a Python shell. Does sds actually contain the data you expect. Does getting the driver succeed? Etc Oct 7, 2016 at 9:31

1 Answer 1


A one-liner would be (if you have gdal installed):

gdal_translate -of aaigrid netcdf:in.nc:Band1 out.txt

EDIT For doing in python

Use subprocess as:

import subprocess
subprocess.call('gdal_translate -of aaigrid netcdf:in.nc:Band1 out.txt')

You can then use the resultant file as normal and continue along with the script in python.

  • Cool idea, unfortunately not in Python! :/
    – countryman
    Feb 23, 2018 at 17:26
  • I have edited my answer to reflect what you want, hope that helps.
    – shahryar
    Feb 24, 2018 at 1:26

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.