写入Shapefile

时间:2016-09-14 01:32:36

标签: python shapefile

我在python中编写/读取Shapefile时遇到了麻烦。我有一个点数组,我想用pyshp写入多边形。代码的相关部分是:

dividedRects = [(7598325.0, 731579.0, 7698325.0, 631579.0), (7598325.0, 631579.0, 7698325.0, 611641.0), (7698325.0, 731579.0, 7728636.0, 631579.0), (7698325.0, 631579.0, 7728636.0, 611641.0)]

def createPolys(dividedRects):
    w = shapefile.Writer(shapefile.POLYGON)
    for i in range(0, len(dividedRects)):
        print i
        topLeft = [dividedRects[i][0],dividedRects[i][1]]
        topRight = [dividedRects[i][2], dividedRects[i][1]]
        bottomRight = [dividedRects[i][2], dividedRects[i][3]]
        bottomLeft = [dividedRects[i][0], dividedRects[i][3]]
        w.poly(parts=[[topLeft,topRight,bottomRight,bottomLeft]])
        w.field("ID", "C", "40")
        w.field("Events", "C", "40")
        w.record(str(i), str(0))
    w.save('cellFile')

createPolys(dividedRects)

这会导致错误:

IndexError                                Traceback (most recent call last)
<ipython-input-36-503affbe838b> in <module>()
----> 1 createPolys(dividedRects)

<ipython-input-35-4c552ae29bc7> in createPolys(dividedRects)
     10         w.field("ID", "C", "40")
     11         w.field("Events", "C", "40")
---> 12         w.record(str(i), str(0))
     13     w.save('cellFile')
     14 #     topLeft = [dividedRects[1][0],dividedRects[1][1]]

C:\Users\Me\Anaconda2\lib\site-packages\shapefile.pyc in record(self, *recordList, **recordDict)
    967         if self.fields[0][0].startswith("Deletion"): fieldCount -= 1
    968         if recordList:
--> 969             [record.append(recordList[i]) for i in range(fieldCount)]
    970         elif recordDict:
    971             for field in self.fields:

IndexError: tuple index out of range

如果我从field删除recordscreatePolys行:

def createPolys(dividedRects):
    w = shapefile.Writer(shapefile.POLYGON)
    for i in range(0, len(dividedRects)):
        print i
        topLeft = [dividedRects[i][0],dividedRects[i][1]]
        topRight = [dividedRects[i][2], dividedRects[i][1]]
        bottomRight = [dividedRects[i][2], dividedRects[i][3]]
        bottomLeft = [dividedRects[i][0], dividedRects[i][3]]
        w.poly(parts=[[topLeft,topRight,bottomRight,bottomLeft]])
#         w.field("ID", "C", "40")
#         w.field("Events", "C", "40")
#         w.record(str(i), str(0))
    w.save('cellFile')

然后,当从文件中读取记录时,我得到一个断言错误:

createPolys(dividedRects)

sf2 = shapefile.Reader("cellFile")
print sf2.records()
shapes = sf2.shapes()
bbox = shapes[1].bbox
#['%.3f' % coord for coord in bbox]
print bbox
points = shapes[1].points
print points

AssertionError                            Traceback (most recent call last)
<ipython-input-37-597af0b882ba> in <module>()
      1 sf2 = shapefile.Reader("cellFile")
----> 2 print sf2.records()
      3 shapes = sf2.shapes()
      4 bbox = shapes[1].bbox
      5 #['%.3f' % coord for coord in bbox]

C:\Users\Me\Anaconda2\lib\site-packages\shapefile.pyc in records(self)
    528         """Returns all records in a dbf file."""
    529         if not self.numRecords:
--> 530             self.__dbfHeader()
    531         records = []
    532         f = self.__getFileObj(self.dbf)

C:\Users\Me\Anaconda2\lib\site-packages\shapefile.pyc in __dbfHeader(self)
    464             self.fields.append(fieldDesc)
    465         terminator = dbf.read(1)
--> 466         assert terminator == b("\r")
    467         self.fields.insert(0, ('DeletionFlag', 'C', 1, 0))
    468 

AssertionError: 

当我删除循环并写了一条记录时,似乎工作正常。发生了什么事?

1 个答案:

答案 0 :(得分:1)

我不知道pyshp库,但我会尝试提供帮助。

两个w.field()命令出现在for循环中。这可能导致多次定义两列“ID”和“事件”。当您只写一个记录(多边形)时,它工作正常(即w.record()命令包含两个值)。在第一次迭代之后,将有4,6等列。这可以解释你描述的行为。

尝试移动w.field()之前的两条for loop行。

当您对w.record()发表评论时,您会获得一个shp(和shx)文件,其中包含与相应dbf文件不同的记录。这解释了阅读时的断言错误。

与您的问题无关,您还可以使用enumerate(内置函数)简化代码。

w = shapefile.Writer(shapefile.POLYGON)
w.field("ID", "C", "40")
w.field("Events", "C", "40")    
for i,rect1 in enumerate(dividedRects):
    print i
    topLeft = [rect1[0],rect1[1]]
    topRight = [rect1[2], rect1[1]]
    bottomRight = [rect1[2], rect1[3]]
    bottomLeft = [rect1[0], rect1[3]]
    ....

(我无法测试,因为我没有pyshp)祝你好运!