[GIS] Updating Attributes using Pyshp

pyshppythonshapefile

Is it possible to update an attribute field in a shapefile using pyshp ?

I went through their documentation and all they show is how to create new attribute rather than editing or updating an already existing one.

If updating is not possible, is there any other recommended Python library for doing the same ?

Best Answer

It is the same thing with pyshp, except that you cannot update directly the dbf file. When you read a shapefile, the data are stored in Python lists

import shapefile
input = shapefile.Reader("yourfile.shp")
shapes = input.shapes() # -> the geometries in a list
fields = input.fields[1:] -> the fields definition in a list
fields_name = = [field[0] for field in fields] -> the fields names in a list
attributes = input.records() -> the attributes in a list

# now you can modify an attribute value in the list:
attributes[0][1] = "what you want" # second attribute of the first record
# if you want to use a field name for the attribute, like in dbfpy, you must use a dictionary
list = [(i,dict(zip(fields, attri))) for i,attri in enumerate(attributes)]
dict = dict((key, value) for (key, value) in list)
# now you can modify an attribute value in the dictionary:
dict[0]['field']='whatyouwant' # attribute of "field" in the first record
# and return to the original attributes list
attributes_cor = [i.values() for i in dict.values()]

but this changes the value in the list or in the dictionary, not in the dbf file. To do this, rather than affecting the original shapefile, it is better to create a copy with the new attribute list (same as Add a Field to an Existing Shapefile or Subsetting a Shapefile by Attributes ).

You can also use other Python libraries like ogr or Fiona (see Using the API of QSpatiaLite plugin for the principles, the data are stored as Python dictionaries)

from shapely.geometry import mapping, shape
import fiona
# Read the original Shapefile
with fiona.collection('yourfile.shp', 'r') as input:
# The output has the same schema
schema = input.schema.copy()
# write a new shapefile
with fiona.collection('yourcopyfile.shp', 'w', 'ESRI Shapefile', schema) as output:
    for elem in input:
         elem['properties']['field'] = 'whatyouwant' # or a function, or...
         output.write({'properties': elem['properties'],'geometry': mapping(shape(elem['geometry']))})
Related Question