python - Pyshp appends new fields but not record values to an existing shapefile -


the problem consists in append columns presented in .csv file new fields existing shapefile. so, i've used python , modules pyshp , csv to, first, copy content of original shapefile (geometries , records) and, second, create new fields in copy , iterate in respective .csv rows in order insert on it:

import os, sys import shapefile, csv  os.path import basename  filename_full = sys.argv[1] output_full = sys.argv[2]  name, file_extension = os.path.splitext(filename_full) output_name, file_extension = os.path.splitext(output_full)  filename_dbf =  name + ".dbf" filename_classified =  name + "_classified.csv" output_dbf =  output_name + ".dbf"  # reader myshp = open(filename_full, "rb") mydbf = open(filename_dbf, "rb") r = shapefile.reader(shp=myshp, dbf=mydbf)  # writer w = shapefile.writer(r.shapetype)  # copy shapefiles content w._shapes.extend(r.shapes()) w.records.extend(r.records()) w.fields = list(r.fields) w.save(output_full)  # add new records csv open(filename_classified, 'rt', encoding='utf-8') csvfile:      reader = csv.dictreader(csvfile, delimiter=',')          headers = reader.fieldnames      [w.field(field) field in headers]           row in reader:                     w.record(*tuple([row[f] f in headers])) # <-- insertion in specific fields  w.save(output_full) 

in pyshp page, there couple of examples. 1 of them specific insertion of rows specific field. follows:

>>> w = shapefile.writer() >>> w.field('first_fld','c','40') >>> w.field('second_fld','c','40') >>> w.record('first', 'line') >>> w.record(first_fld='first', second_fld='line') 

but, indicating fields, get:

traceback (most recent call last):   file "assigning-shapefile.py", line 68, in <module>     w.record(*tuple([row[f] f in headers]))   file "/usr/local/lib/python3.5/dist-packages/shapefile.py", line 1040, in record     record = [recordlist[i] in range(fieldcount)]   file "/usr/local/lib/python3.5/dist-packages/shapefile.py", line 1040, in <listcomp>     record = [recordlist[i] in range(fieldcount)] indexerror: tuple index out of range  

and, if inside shapefile, have this:

qgis attribute table before , after code execution

which concluded fields successful added, rows (w.record fields name specified) not.


Comments

Popular posts from this blog

angular - Ionic slides - dynamically add slides before and after -

minify - Minimizing css files -

Add a dynamic header in angular 2 http provider -