Pyshp: Pure Python ESRI Shapefile Reader/Writer

3.0.3 · active · verified Thu Apr 09

Pyshp (The Python Shapefile Library) is a pure Python library designed for reading and writing ESRI Shapefile format files. It allows developers to work with geospatial vector data without external dependencies. The library is currently in version 3.0.3 and maintains an active development and release cadence.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to create a simple shapefile, write point geometries and their attributes, then read them back. It also shows how to create a polygon shapefile with multiple parts (including a hole), setting the shape type and adding fields and records. Using context managers ensures files are properly closed.

import shapefile
import os

# Create a dummy shapefile for reading example
output_dir = 'temp_shapefile_dir'
os.makedirs(output_dir, exist_ok=True)

w = shapefile.Writer(os.path.join(output_dir, 'test_points.shp'))
w.field('name', 'C')
w.point(1, 1)
w.record('Point A')
w.point(2, 2)
w.record('Point B')
w.close()

# Reading a shapefile
# You specify the base filename of the shapefile or any of its component files.
# Using a context manager is recommended for automatic file closing.
with shapefile.Reader(os.path.join(output_dir, 'test_points.shp')) as sf:
    print(f"Shape type: {sf.shapeTypeName}")
    print(f"Number of shapes: {len(sf.shapes())}")
    for shapeRec in sf.iterShapeRecords():
        print(f"Geometry: {shapeRec.shape.points}, Record: {shapeRec.record}")

# Writing a new shapefile
with shapefile.Writer(os.path.join(output_dir, 'new_polygon.shp')) as w:
    w.shapeType = shapefile.POLYGON
    w.field("Name", "C")
    w.field("Area", "N")
    
    # Add a polygon
    w.poly([[[0,0],[0,10],[10,10],[10,0],[0,0]]])
    w.record("Square", 100)

    # Add another polygon with a hole
    w.poly([
        [[20,20],[20,30],[30,30],[30,20],[20,20]], # Outer ring
        [[22,22],[22,28],[28,28],[28,22],[22,22]]  # Inner ring (hole)
    ])
    w.record("Donut", 56)

print(f"Shapefile '{os.path.join(output_dir, 'new_polygon.shp')}' created successfully.")

# Clean up (optional)
# for ext in ['.shp', '.shx', '.dbf', '.prj']: # .prj might not be created by default
#     if os.path.exists(os.path.join(output_dir, 'new_polygon' + ext)):
#         os.remove(os.path.join(output_dir, 'new_polygon' + ext))
#     if os.path.exists(os.path.join(output_dir, 'test_points' + ext)):
#         os.remove(os.path.join(output_dir, 'test_points' + ext))
# os.rmdir(output_dir)

view raw JSON →