I'm trying to write some Python code in QGIS which merge together lots of polygons from a layer. When a line is drawn over the polygons, the polygons which intersect the line are merged together.
But I'm getting an error
Traceback (most recent call last): File "C:\PROGRA~1\QGIS31~1.8\apps\Python39\lib\code.py", line 90, in runcode exec(code, self.locals) File "", line 1, in AttributeError: 'NoneType' object has no attribute 'GetLayerDefn'
after lines
merged_feature = ogr.Feature(merged_layer.GetLayerDefn())
Where am I going wrong?
from osgeo import ogr
# Open the input shapefile
input_shapefile = ogr.Open("d:\MAPS\input_new.shp", 1)
layer = input_shapefile.GetLayer()
# Open the line shapefile
input_shapefile = ogr.Open("d:\MAPS\line_table.shp", 2)
layer = input_shapefile.GetLayer()
# Create a new shapefile for the merged polygons
merged_shapefile = ogr.GetDriverByName("ESRI Shapefile").CreateDataSource("d:\MAPS\merged.shp")
merged_layer = merged_shapefile.CreateLayer("merged", layer.GetSpatialRef(), ogr.wkbPolygon)
# Iterate over the features in the input layer
for feature in layer:
# Check if the feature intersects with the line
if feature.Intersects(line_table):
# Add the feature's geometry to the merged polygon
geometry = feature.GetGeometryRef()
if merged_geometry is None:
merged_geometry = geometry.Clone()
else:
merged_geometry = merged_geometry.Union(geometry)
# If the feature does not intersect with the line, add it to the merged layer as-is
else:
merged_layer.CreateFeature(feature)
# Create a new feature in the merged layer for the merged polygon
merged_feature = ogr.Feature(merged_layer.GetLayerDefn())
merged_feature.SetGeometry(merged_geometry)
merged_layer.CreateFeature(merged_feature)
# Close the shapefiles
input_shapefile = None
merged_shapefile = None
1 Answer 1
There are a few points where it could fail, but most likely unable to find the file, or directory where it wants to create the file. Try testing your parameters once they are set, like in the example below.
eg:
if input_shapefile is not None:
layer input_shapefile.GetLayer()
else:
print("Shapefile cannot be found")
exit()
or something similar. Insertion of simple 'check of null/None' tests will help you debug and make your program more robust at the same time.
"d:\MAPS\input_new.shp"
tor"d:\MAPS\input_new.shp"
or the shapefile path can be incorrect, see: geeksforgeeks.org/python-raw-strings