Calculate area of polygons using OGR in python script
I ran your script (slightly modified) at the Python Console of QGIS:
from osgeo import ogr vlayer = iface.activeLayer() provider = vlayer.dataProvider() path = provider.dataSourceUri() tmp = path.split("|") path_to_shp_data = tmp driver = ogr.GetDriverByName("ESRI Shapefile") dataSource = driver.Open(path_to_shp_data, 1) layer = dataSource.GetLayer() new_field = ogr.FieldDefn("Area", ogr.OFTReal) new_field.SetWidth(32) new_field.SetPrecision(2) #added line to set precision layer.CreateField(new_field) for feature in layer: geom = feature.GetGeometryRef() area = geom.GetArea() print area feature.SetField("Area", area) layer.SetFeature(feature) dataSource = None
and it worked (see next image).
However, the precision of values (0 decimal) at the field "Area" is different to values printed at the Python Console:
As you are pointed out that your printed areas are very small (0.00000x) and likely do not reflect square meters, this is the reason for your resulting "Area" field contains all 0's. Probably, you have a projection problem in your shapefile. It is not in meters.
I included the code line to set the precision (2 decimals) of 'Area' field and it worked.
Your code is perfect. I think you are not working in a projection in meters e.g mollweide.
All you need to do is reproject the layer to -- +proj=moll +lon_0=0 +x_0=0 +y_0=0 +ellps=WGS84 +datum=WGS84 +units=m no_defs
Then run the code again and it would be 100%