I have experienced a very bizarre issue with my PyQgis code. I simply want to load a raster and a vector layer to do zonal statistics, the first part works perfectly but for the zonal statistic I have got an error with this command:
raster file = qgis.utils.iface.mapCanvas().layer(1).source()
(AttributeError: 'NoneType' object has no attribute 'source')
The strange thing is that if I rerun only the second part of the code (ie. my layers are already loaded) the extension .source() does not report any errors. This is still annoying since I am not able to write a loop with the full code and then use it for different layers.
Did anyone already experience this kind of issue?
Here is the code,
os.chdir("C:\Projet")
### Part I
## load vector layer
vbaselayer = QgsVectorLayer("county_save_as_lamhert_onlyUS.shp", "basemap", "ogr")
## load and project the raster layer
os.system('gdalwarp -overwrite -t_srs EPSG:102004 -of GTiff NETCDF:"rhum.2m.2000.nc":rhum rhum_projection.tif')
humidity = "rhum_projection.tif"
fileInfo = QFileInfo(humidity)
rlayer = QgsRasterLayer(humidity,"hum2000")
rlayer.isValid()
QgsMapLayerRegistry.instance().addMapLayer(rlayer)
QgsVectorFileWriter.writeAsVectorFormat(vbaselayer,"2000.shp","utf-8",None,"ESRI Shapefile")
year = 2000
vlayer = QgsVectorLayer("{}.shp".format(year), "county", "ogr")
vlayer.isValid()
QgsMapLayerRegistry.instance().addMapLayer(vlayer)
### Part II
## zonal statistics
id = 1
while id < 365:
vectorlayer=qgis.utils.iface.mapCanvas().layer(0)
rasterfile = qgis.utils.iface.mapCanvas().layer(1).source()
zonalstats = qgis.analysis.QgsZonalStatistics(vectorlayer,rasterfile,str(id),id)
zonalstats.calculateStatistics(None)
id += 1
raster_file = qgis.utils.iface.mapCanvas().layers()[1].source()
, didn't you?vectorlayer=qgis.utils.iface.mapCanvas().layer(0) rasterfile = qgis.utils.iface.mapCanvas().layer(1).source() zonalstats = qgis.analysis.QgsZonalStatistics(vectorlayer,rasterfile,str(1),1) zonalstats.calculateStatistics(None)
layer(1)
. Could you post how are you loading your layers, i.e., provide a reproducible code snippet?