pygdal

3.6.4.11 · maintenance · verified Thu Apr 16

pygdal provides virtualenv and setuptools friendly Python bindings for the GDAL (Geospatial Data Abstraction Library) C API. It was created to address installation difficulties with the standard GDAL Python bindings for GDAL versions prior to 3.7. The project maintains a 3.6.* release line as the last for GDAL versions before 3.7, after which GDAL can be installed directly from PyPI. It focuses on offering a more 'pythonic' interface and integrates with NumPy for data handling.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to open a geospatial raster file (GeoTIFF) using `pygdal` and retrieve basic metadata. It also shows how to explicitly enable GDAL exceptions for better error handling, which is often recommended as GDAL bindings typically return `None` on error by default.

from osgeo import gdal
import os

def open_gdal_dataset(filepath):
    """Opens a GDAL dataset and prints some basic information."""
    if not os.path.exists(filepath):
        print(f"Error: File not found at {filepath}")
        return

    # Enable GDAL exceptions for clearer error handling
    gdal.UseExceptions()
    try:
        dataset = gdal.Open(filepath, gdal.GA_ReadOnly)
        if dataset is None:
            print(f"Could not open {filepath}")
            return

        print(f"Successfully opened: {filepath}")
        print(f"Driver: {dataset.GetDriver().LongName} ({dataset.GetDriver().ShortName})")
        print(f"Size: {dataset.RasterXSize}x{dataset.RasterYSize}x{dataset.RasterCount}")
        print(f"Projection: {dataset.GetProjection()[:50]}...") # Print first 50 chars
        print(f"GeoTransform: {dataset.GetGeoTransform()}")
        # Close the dataset implicitly when `dataset` goes out of scope, or explicitly with dataset=None
    except Exception as e:
        print(f"An error occurred: {e}")

# Example usage (requires a dummy GeoTIFF file, or replace with an existing file path)
# Create a dummy file for demonstration if it doesn't exist
dummy_tif = "dummy.tif"
if not os.path.exists(dummy_tif):
    driver = gdal.GetDriverByName("GTiff")
    rows, cols = 100, 100
    dataset = driver.Create(dummy_tif, cols, rows, 1, gdal.GDT_Byte)
    dataset.SetGeoTransform((0, 1, 0, 0, 0, -1))
    dataset.SetProjection('GEOGCS["WGS 84",DATUM["WGS_1984",SPHEROID["WGS 84",6378137,298.257223563,AUTHORITY["EPSG","7030"]],AUTHORITY["EPSG","6326"]],PRIMEM["Greenwich",0,AUTHORITY["EPSG","8901"]],UNIT["degree",0.0174532925199433,AUTHORITY["EPSG","9122"]],AUTHORITY["EPSG","4326"]]')
    band = dataset.GetRasterBand(1)
    band.WriteArray([[i % 255 for i in range(cols)] for _ in range(rows)])
    dataset = None # Close the dataset

open_gdal_dataset(dummy_tif)
# Clean up dummy file
os.remove(dummy_tif)

view raw JSON →