Skip to content

Instantly share code, notes, and snippets.

@chingchai
Created July 21, 2019 15:33
Show Gist options
  • Save chingchai/43a7ffc33ddfe49225780dcf1f0c3a18 to your computer and use it in GitHub Desktop.
Save chingchai/43a7ffc33ddfe49225780dcf1f0c3a18 to your computer and use it in GitHub Desktop.
Get Shapefile Field and Type in PyQGIS
# -*- coding: utf-8 -*-
# Get Shapefile Field and Type in PyQGIS
# Author : CHINGCHAI HUMHONG
# Copyright 2019. All rights reserved.
import os
import sys
from osgeo import ogr
location = r"C:\Workspace\pyqgis\pl_village.shp"
dataSource = ogr.Open(location)
lyr = dataSource.GetLayer(0)
lyrDefinition = lyr.GetLayerDefn()
print("Shapefile in a directory : " + location)
print("FieldName -> Type Width Precision")
for i in range(lyrDefinition.GetFieldCount()):
fieldName = lyrDefinition.GetFieldDefn(i).GetName()
fieldTypeCode = lyrDefinition.GetFieldDefn(i).GetType()
fieldType = lyrDefinition.GetFieldDefn(i).GetFieldTypeName(fieldTypeCode)
fieldWidth = lyrDefinition.GetFieldDefn(i).GetWidth()
fieldPrecision = lyrDefinition.GetFieldDefn(i).GetPrecision()
print (fieldName + " -> " + fieldType + " " + str(fieldWidth)+ " " + str(fieldPrecision))
print ("\n")
print ("*" * 30)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment