2

I am trying to list all the columns (or features) and their types for a shapefile. shp2pgsql shows following schema:

CREATE TABLE "liberia" (gid serial,
"local_name" varchar(100),
"eng_name" varchar(100),
"cntry_name" varchar(75),
"type" varchar(75),
"cntry_code" varchar(10),
"continent" varchar(50),
"iso_code" varchar(10),
"volume" int4,
"id_7_1" varchar(100),
"id" numeric(10,0));
ALTER TABLE "liberia" ADD PRIMARY KEY (gid);
SELECT AddGeometryColumn('','liberia','geom','5578','MULTIPOLYGON',2);

The following code snippet tries to achieve that:

 from osgeo import ogr
 reader = ogr.Open("file.shp")
 x = reader.GetLayer(0)
 fields  = x.schema
 for l in ll:
    print l.GetName()
    print l.GetType()

Which prints output as follows:

LOCAL_NAME
4
ENG_NAME
4
CNTRY_NAME
4
...

I am facing two problems. One the geom column/feature is missing from the list and second deciphering type id to python or postgres type.

3

I will address the problems seperately:

Type of shapefile column

The schema function is actually a wrapper around the GetFieldDefn() and GetLayerDefn() functions:

output = [] 
defn = self.GetLayerDefn() 
for n in range(defn.GetFieldCount()): 
    output.append(defn.GetFieldDefn(n)) 
return output 

(source code)

The individual entries l you iterate over are therefore instances of OGRFieldDefn (Documentation). They have a function called GetFieldTypeName(Type) that you can use:

for l in ll:
    type = l.GetType()
    type_name = l.GetFieldTypeName(type)
    print type_name
    print l.GetName()

Accessing the geometry

You can iterate over the features in a shapefile as usual:

from osgeo import ogr
reader = ogr.Open("file.shp")
for feat in reader.GetLayer():
    geom = feat.GetGeometryRef()
    # geom is now an ogr geometry object
    print geom.ExportToWkt()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.