0

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? – bugmenot123 Oct 5 '16 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 '16 at 12:23
  • No I meant unrolling the loop. Does it work if you just try to write the first subdata set? – bugmenot123 Oct 6 '16 at 11:07
  • Unfortunately not...does this give any hint? – countryman Oct 7 '16 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 – bugmenot123 Oct 7 '16 at 9:31
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 '18 at 17:26
  • I have edited my answer to reflect what you want, hope that helps. – shahryar Feb 24 '18 at 1:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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