You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python用OGR库向Shapefile追加要素时创建要素返回错误码6

Fixing Error Code 6 When Adding Features to an ESRI Shapefile with OGR

Hey there, let's figure out why you're hitting error code 6 (which maps to OGRERR_UNSUPPORTED_OPERATION in OGR) when trying to append features to your shapefile. I've run into this exact gotcha before, so let's walk through the fixes step by step.

First off, the biggest red flag in your code snippet is how you're opening the shapefile:

data_source = driver.Open(src, 0)

That 0 parameter means you're opening the file in read-only mode—you can't add or modify features that way! You need to use 1 for write access. That's almost certainly the main cause of your error code 6.

But let's go beyond just that to make sure your entire feature-addition workflow is solid. Here's a complete, corrected example that covers all the necessary steps:

Complete Working Code

# -*- coding: utf-8 -*-
from osgeo import ogr
import os

def add_new_feature(src):
    # Grab the ESRI Shapefile driver
    driver = ogr.GetDriverByName('ESRI Shapefile')
    if not driver:
        raise Exception("Whoops, couldn't find the ESRI Shapefile driver!")
    
    # Open the shapefile in WRITE mode (1 = write access)
    data_source = driver.Open(src, 1)
    if not data_source:
        raise Exception(f"Failed to open {src} in write mode—check permissions or if it's locked!")
    
    # Get the layer from the shapefile
    in_layer = data_source.GetLayer()
    if not in_layer:
        raise Exception("Couldn't retrieve the layer from the shapefile.")
    
    # Get the layer's schema to create a matching feature
    layer_def = in_layer.GetLayerDefn()
    
    # Create a new feature that matches the layer's structure
    new_feature = ogr.Feature(layer_def)
    
    # --- Set your feature attributes here (customize this!) ---
    # Example: If your layer has a string field called "Location"
    new_feature.SetField("Location", "My New Point")
    # Example: If you have an integer field called "ID"
    new_feature.SetField("ID", 456)
    
    # --- Set the feature's geometry (customize this too!) ---
    # Let's use a point as an example—swap with your geometry type (line/polygon)
    point_geom = ogr.Geometry(ogr.wkbPoint)
    point_geom.AddPoint(-122.4194, 37.7749)  # X, Y coordinates (SF example)
    new_feature.SetGeometry(point_geom)
    
    # Add the feature to the layer
    add_result = in_layer.CreateFeature(new_feature)
    if add_result != 0:
        raise Exception(f"Failed to add feature—error code: {ogr.GetLastErrorNo()}")
    
    # Critical: Save changes to disk
    in_layer.SyncToDisk()
    
    # Clean up resources to avoid memory leaks
    new_feature.Destroy()
    data_source.Destroy()
    
    print("Feature added successfully! 🎉")

# Run the function with your shapefile path
shapefile_path = r"myShapefile.shp"
add_new_feature(shapefile_path)

Key Fixes & Things to Remember:

  • Write Access: Using driver.Open(src, 1) instead of 0 is non-negotiable for modifying the shapefile.
  • Locking: Make sure no other programs (like QGIS, ArcGIS) have the shapefile open—they'll lock it, causing write failures.
  • Schema Matching: Your new feature must match the layer's schema exactly (correct field types, geometry type). If you're unsure, check the shapefile's properties in a GIS tool.
  • Sync to Disk: Calling in_layer.SyncToDisk() ensures your changes are saved—don't skip this step, or your feature won't show up!
  • Cleanup: Explicitly destroying features and data sources helps prevent memory leaks, especially in longer scripts.

If you still get error code 6 after fixing the write mode, double-check your file permissions and make sure the shapefile isn't corrupted.

内容的提问来源于stack exchange,提问作者Yorian

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 02:29:50