7

I am trying to strip data out of an existing shapefile to create new shapefiles. I have made the loop work, and made the new file, but I cannot work out why I cannot add records to the new file I am writing:

import shapefile as shp


coord1 = (39.737094, -121.543857)
coord2 = (39.651237, -121.403610)

sfinput = shp.Reader(r'C:\...\fire_archive_M6_98806.shp')
w = shp.Writer(r'C:\...\Output')
w.fields = sfinput.fields


for i in range(len(sfinput.records())):
    #test if within latitude
    if sfinput.record(i)[0] >= coord2[0] and sfinput.record(i)[0] <= coord1[0]:
        #test if within longitude
        if sfinput.record(i)[1] <= coord2[1] and sfinput.record(i)[1] >= coord1[1]:
            w.record(sfinput.record(i))

The error I am recieving:

record = [recordList[i] for i in range(fieldCount)]
IndexError: tuple index out of range
2
  • fieldCount sounds like the number of attributes, while recordList sounds like the number of records.
    – inc42
    Jan 18, 2020 at 12:48
  • I have worked out how to set one record to the shape file that I am writing: w.record=sfinput.record(i) This just seems to write over the record already assigned to w though
    – ushham
    Jan 18, 2020 at 16:16

1 Answer 1

8
import shapefile as shp

sfinput = shp.Reader(r"C:\...\fire_archive_M6_98806.shp")

with shp.Writer(r"C:\...\Output") as w:
    w.fields = sfinput.fields[1:] # skip first deletion field
    for feature in sfinput.iterShapeRecords(): # iteration on both record and shape for a feature
            w.record(*feature.record) # * for unpacking tuple
            w.shape(feature.shape)

shapefile doesn't manage CRS, therefore don't forget to copy .prj file.

import os
import shutil
prj_file = r"C:\...\fire_archive_M6_98806.prj"
if os.path.exists(prj_file):
    shutil.copy(prj_file, r"C:\...\Output.prj")

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.