These are the exact names that OGR recognizes; in parentheses are the file extensions, not to be included in the driver name:
- ESRI Shapefile (*.shp)
- KML (*.kml)
- AVCE00 (*.e00)
- AVCBin
- CSV (*.csv)
- GeoJSON (*.json)
- GML (*.gml)
try:
from osgeo import ogr
except ImportError:
import ogr
driver = ogr.GetDriverByName(‘Driver Code’)
os.chdir(‘/usr/bin/blah/’)
dataSource = driver.Open(filename, 0) # 0: read-only, 1: writeable
layer = dataSource.GetLayer(index) # index is usually 0 (for SHP)
# The filename argument is a string
dataSource = driver.CreateDataSource(filename)
layer = dataSource.CreateLayer(‘name’, geom_type=ogr.wkbPoint)
# After adding fields, get the layer definition
featureDefn = layer.GetLayerDefn()
# Create a feature from scratch
feature = ogr.Feature(featureDefn)
# Set the geometry for the new feature
feature.SetGeometry(point)
# Populate the attribute table
feature.SetField(‘field_name’, value)
# Field edits need to be set each time made
layer.SetFeature(feature)
# Finally, feature must be written to the layer
layer.CreateFeature(feature)
# Close data source at the very end with Destroy() so that everything is written to disk
dataSource.Destroy()
# Count number of features
numFeatures = layer.GetFeatureCount()
# Returns geographic extent as a tuple where i=0: upper; i=1: left; i=2: right; i=3: lower
extent = layer.GetExtent()
extent[i]
# Grab a feature by its FID
feature = layer.GetFeature(fid)
# Grabs next feature every time called
feature = layer.GetNextFeature()
while feature:
feature = layer.GetNextFeature()
# Call to reset pointer and loop again
layer.ResetReading()
# The name argument is the attribute name as a string
value = feature.GetField(name)
value = feature.GetFieldAsString(name)
value = feature.GetFieldAsInteger(name)
# Return the feature’s geometry (point, polygon...)
geometry = feature.GetGeometryRef()
# Point objects have GetX() and GetY() methods
x = geometry.GetX()
y = geometry.GetY()
feature.Destroy()
dataSource.Destroy()
# Check that a file exists, delete the object
import os
if os.path.exists(filename):
driver.DeleteDataSource(filename)
# Shapefiles must be empty to add fields; field names have a 12-character limit
fieldDefn = feature.GetFieldDefnRef(‘field_name’) # fid also works in place of name
fieldDefn = ogr.FieldDefn(‘field_name’, ogr.OFTString) # Also: ogr.OFTInteger
fieldDefn.SetWidth(x) # Where argument x is an integer
# Create a field with the field definition
layer.CreateField(fieldDefn)
# Close data source at the very end with Destroy() so that everything is written to disk
dataSource.Destroy()