I have been using gdal from the command line to convert an asc file to a GeoJSON output. I can do this successfully:

gdal_polygonize.py input.asc -f "GeoJSON" output.json

Now I wish to use Python and follow this process for a range of files.

import gdal
import glob
for file in glob.glob("dir/*.asc"):
    new_name = file[:-4] + ".json"
    gdal.Polygonize(file, "-f", "GeoJSON", new_name)

Hpwever, for exactly the same file I get the following error TypeError: in method 'Polygonize', argument 1 of type 'GDALRasterBandShadow *'

Why does the command line version work and the python version not?

1 Answer 1


You are confusing the use of the gdal_polygonize command line utility with the python function gdal.Polygonize().

As you mentioned, you've managed to use the command line utility successfully; however, the Python function works differently and expects different arguments than those specified in the utility. The first argument should be a GDAL Band object, not a string, so this is why you get your error.

To get the Band object you need to open the input file using gdal.Open() and use the GetRasterBand() method to get your intended band. Additionally, you need to create an output layer in which the resulting polygons will be created.

The Python GDAL/OGR Cookbook has a good example on how to use this function. The required parameters are explained in a bit more detail here.


Following on from your comment, if you would prefer to keep using the command line utility, one solution is to call it from within a Python script using the subprocess module i.e.

import subprocess

for in_file in glob.glob("dir/*.asc"):
    out_file = in_file[:-4] + ".json"

This loops through the files and updates the input/output paths.

This way you get the result that you are use to getting from the utility, but the ability to loop through your files. If you do plan on going this way, the subprocess documention will be useful.

  • Thanks Ali! Very useful. One question - How do I specify all bands? The GetRasterBand function in the example takes an integer (srcband = src_ds.GetRasterBand(1)), I want the conversion for the entire file (as the command line does) Commented Oct 19, 2016 at 9:34
  • No problem. To do this for all bands you will have to loop through them. You can find out how many bands there are using the RasterCount attribute.
    – Ali
    Commented Oct 19, 2016 at 9:39
  • Happy days - the count was 1 ;) Thanks Ali! Commented Oct 19, 2016 at 10:40
  • I've updated my answer to provide an alternative method you could use for looping through your files. Happy Pythoning!
    – Ali
    Commented Oct 19, 2016 at 11:27

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.