Can anyone tell what is wrong with this code?

import h5py, gdal, osr,gdalconst
from gdalconst import *

for f in os.listdir(directory):                    
    filename = os.fsdecode(f)

the print(g) gives a none output.

  • Null output means that open failed: gdal.org/gdal_tutorial.html Note that if GDALOpen() returns NULL it means the open failed, and that an error messages will already have been emitted via CPLError(). Do you have some files that GDAL understands in "filename"? – user30184 Aug 14 '17 at 7:44
  • What are you actually trying to do? Printing the info on a list of datasets? – Kersten Aug 14 '17 at 8:43
  • filename refers to tif files in that specified folder. i want to run some calculations on the pixel values of that tif file. the above code is a part of a long code.when i run it, it says that none object type has no attribute called get.rasterBand(1). so i broke the code and made it print the name of the file(print(g)) and it returned none while print(filename) prints the name of the file. – rao Aug 14 '17 at 8:58

There are multiple inconsistencies with your original code so I'll try to adress them one by one:

It is considered good Python form to only import what you actually use, in your case that would be

import os
from osgeo import gdal

os.listdir returns a list of filenames in your path3. In order to perform any operation based on that list you need to move your code inside the loop. In your case only the last file will be stored in filename and passed to gdal.Open instead of all of them one after another. Additionally you need to pass the full path to the file instead of just the filename, unless the files are in your current working directory.

path3 = 'D:/state_subsets'

for filename in os.listdir(directory):                    
    g = gdal.Open(os.path.join(path, filename), GA_ReadOnly)
    # insert other calculations here
    g = None

In your example g likely produces a None output because it tries to open filename but is not able to find it in the current working directory.

  1. Very strange imports. Normally should be: from osgeo import gdal. There do you get GDAL Python?
  2. Very strange spatial dataset D:/state_subsets is it raster or vector and what is format?

This is official example for raster:

from osgeo import gdal
dataset = gdal.Open( filename, GA_ReadOnly )
if dataset is None:
   # report error

And for vector:

from osgeo import gdal
ds = gdal.OpenEx( "point.shp", gdal.OF_VECTOR )
if ds is None:
    print "Open failed.\n"
    sys.exit( 1 )

See this and this tutorials.

  • 2
    gdal.org/gdal_tutorial.html may use old syntax but it does have import gdal from gdalconst import * in the "Opening the File" example. Perhaps it needs some updates. – user30184 Aug 14 '17 at 8:00

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.