Geography Reference
In-Depth Information
Let's take a look at the code in chunks and go through it bit by bit:
Download import_volcanoes.py
# import the csv module
Line 1
import csv
-
# import the OGR modules
-
import ogr
-
import osr
5
-
-
# use a dictionary reader so we can access by field name
reader = csv.DictReader(open("volcano_data.txt","rb"),
-
delimiter='\t',
-
quoting=csv.QUOTE_NONE)
10
Beginning with line 2, we import the modules needed for the script.
The csv module is part of Python as of version 2.3. It provides a simple
way to read a delimited text file and is well suited to our needs. The
other imports we need are ogr , which provides access to the OGR func-
tions needed to create and write features to a shapefile and osr , which
provides the spatial reference functions.
Next we set up the csv reader in line 8. We are using the DictReader class
to read the file and map the information into a dict . This allows us to
reference the data using the field names in the header row of the input
file. We'll use this capability to pick and choose which fields we want
in our shapefile. When creating the DictReader , we need to specify the
delimiter, in this case \t for the tab character. You might remember we
used the same with the QGIS Delimited Text plugin. The last argument
in setting up the reader is cvs.QUOTE_NONE , which specifies that our file
has no quotes around the data.
Now we're ready to use the OGR bindings to create the shapefile:
Download import_volcanoes.py
# set up the shapefile driver
Line 1
driver = ogr.GetDriverByName("ESRI Shapefile")
-
-
-
# create the data source
data_source = driver.CreateDataSource("volcanoes.shp")
5
-
-
# create the spatial reference
srs = osr.SpatialReference()
-
srs.ImportFromEPSG(4326)
-
10
-
# create the layer
layer = data_source.CreateLayer("volcanoes", srs, ogr.wkbPoint)
-
-
 
Search WWH ::




Custom Search