Take the 2-minute tour ×
Geographic Information Systems Stack Exchange is a question and answer site for cartographers, geographers and GIS professionals. It's 100% free, no registration required.

I am using the popular QSpatiaLite plugin for QGIS. Since I am creating and modifying SpatiaLite tables directly with Python (using pyspatialite), I wonder whether I can automate tasks such as converting from a Shapefile to SpatiaLite directly from the Python code (similar to the plugin's "Import OGR files").

Thus, does the plugin provide some sort of an API to do that kind of stuff? Or can I do this from within pyspatialite without using any QGIS-related API?

I know there is a QGIS Python API but I have never dealt with it, that's why I am kind of confused here.

share|improve this question
    
You can definitely do that sort of conversion (shp -> spatialite) in a range of command-line and script ways. Do you have a full list of the required conversions, or some specific requirements? –  BradHards Apr 4 '13 at 20:02
    
Hi Brad, the only thing I actually need to do is convert an existing SHP in SRID:4326 to a SpatiaLite polygon table, also of SRID:4326, and yes, I would like to do this inside a Python script. –  wnstnsmth Apr 4 '13 at 20:10
add comment

1 Answer 1

up vote 3 down vote accepted

If you use Python, you can perfectly use one of the modules that can read shapefiles like ogr, Fiona or Pyshp to extract the geometries and the attributes of a shapefile and insert them into SQLite/SpatiaLite with pyspatialite without QGIS and QSpatiaLite.

With pyshp (result = Python lists)

import shapefile
input = shapefile.Reader("joinpolypt.shp")
# fields
input.fields[1:]
[['test', 'N', 1, 0], ['color', 'C', 80, 0]]
# geometries and attributes of the layer
shapes = input.shapes()
attributes = input.records()
# first record
shapes[0].points[0]
[273781.244220372, 154668.35103545961]
attributes[0]
[1, 'red']
.....

With Fiona (result = Python dictionaries):

import fiona
points = fiona.open('testpoint.shp')
# schema of the shapefile
points.schema
{'geometry': 'Point', 'properties': {u'test': 'int', u'color': 'str'}}
# first point
points.next()
{'geometry': {'type': 'Point', 'coordinates': (273781.244220372, 154668.35103545961)}, 'id': '0', 'properties': {'test': 1, 'color': u'red'}}
 ...

It is similar with ogr.

In all the cases you get the geometries and the attributes as lists or dictionaries

Then it is easy to use pyspatialite to incorporate these values ​​in a spatialite database.

Note that with OGR 1.10, the GDAL/OGR library can be loaded as a SQLite extension (like spatialite) and you can use directly Python and ogr (SQLite / Spatialite RDBMS)

share|improve this answer
    
Thank you, Fiona works like a charm! –  wnstnsmth Apr 5 '13 at 7:54
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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