Extracting EPSG from a raster using gdal bindings in Python

I found the following workaround. I am unsure if it is the most efficient, but it does work for me.

import gdal
import osr

path = r"C:\temp\test2.tif"
d = gdal.Open(path)
proj = osr.SpatialReference(wkt=d.GetProjection())

EDIT: Slightly more condensed

You can also do this in one line using gdal.Info as so:

epsg = int(gdal.Info(input, format='json')['coordinateSystem']['wkt'].rsplit('"EPSG","', 1)[-1].split('"')[0])

This does essentially the same thing as the answer provided by Lennert. It reads the WKT representation of the file's spatial reference, then parses the string to extract the EPSG.

Note that this method is slightly more robust because gdal.Info is very flexible with the types of inputs it can take. input may be a datasource, valid filepath, or anything within gdal's extensive virtual file systems, which allows this method to accommodate a large number of potential use cases.

I would highly recommend using rasterio, which has a handy python API. For example:

>>> with rasterio.open('/path/to/your/geotiff.tif') as src:
        print (src.crs)

CRS({'init': u'epsg:32615'})