Book Image

Python Geospatial Analysis Cookbook

Book Image

Python Geospatial Analysis Cookbook

Overview of this book

Table of Contents (20 chapters)
Python Geospatial Analysis Cookbook
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Other Geospatial Python Libraries
Mapping Icon Libraries
Index

Batch exporting a list of tables from PostGIS to Shapefiles


We will now change direction and take a look at how we can batch export a list of tables from our PostGIS database into a folder of Shapefiles. We'll again use the ogr2ogr command-line tool from within a Python script so that you can include it in your application programming work flow. Near the end, you can also see how all this works in one single command line.

How to do it...

  1. The following script will fire the ogr2ogr command and loop over a list of tables to export the Shapefile format into an existing folder. So, let's take a look at how to do this as follows:

    #!/usr/bin/env python
    # -*- coding: utf-8 -*-
    #
    import subprocess
    import os
    
    # folder to hold output Shapefiles
    destination_dir = os.path.realpath('../geodata/temp')
    
    # list of postGIS tables
    postgis_tables_list = ["bikeways", "highest_mountains"]
    
    # database connection parameters
    db_connection = """PG:host=localhost port=5432 user=pluto
            dbname=py_geoan_cb password...