【问题标题】:Editing shapefiles in Python via new Writer object isn't working通过新的 Writer 对象在 Python 中编辑 shapefile 不起作用
【发布时间】:2017-12-22 23:27:26
【问题描述】:

我目前正在学习 Joel Lawhead 编写的 Python 地理空间分析教程,但在尝试编辑 shapefile 时遇到了错误。

我正在使用的 shapefile 可以通过 http://git.io/vLd8Y 获得。我在 python3 上的 Jupyter Notebook 中运行我的代码。

这是我的代码。我只是将 shapefile 读取为 Reader 对象r,并创建一个新的 Writer 对象w,其 shapetype 与r 相同。然后,我尝试将记录从r 附加到w

import shapefile
r = shapefile.Reader("NYC_MUSEUMS_GEO")
w = shapefile.Writer(r.shapeType)
w.fields = list(r.fields)
w.records.extend(r.records())

但是,我遇到了这个错误:

AttributeError                            Traceback (most recent call last)
<ipython-input-151-ceee096fbafa> in <module>()
      6 w = shapefile.Writer(r.shapeType)
      7 w.fields = list(r.fields)
----> 8 w.records.extend(r.records())

AttributeError: 'Writer' object has no attribute 'records'

有什么想法吗?

【问题讨论】:

  • 这是 PyShp 2 的一个变化。我无法使 PyShp 2 编写器对象工作,因此恢复为 pip install pyshp==1.2.12 w.records.extend(r.records()) 工作。

标签: python gis shapefile


【解决方案1】:

我也遇到了同样的问题。看来w.records.extend(r.records())在新版本的pyshp中已经不能做了。现在正确的方法是:

for shaperec in r.iterShapeRecords():
   w.record(*shaperec.record)
   w.shape(shaperec.shape)

请参阅上述代码here 周围的更改说明和更多上下文。

【讨论】:

    【解决方案2】:

    我无法重现您描述的问题。我开始了:

    $ python
    Python 3.5.4 (default, Oct  9 2017, 12:07:29) 
    >>>
    

    并安装pyshp 模块:

    $ pip install pyshp
    ...
    Successfully installed pyshp-1.2.12
    

    现在:

    $ python
    Python 2.7.13 (default, Dec  1 2017, 09:21:53) 
    [GCC 6.4.1 20170727 (Red Hat 6.4.1-1)] on linux2
    Type "help", "copyright", "credits" or "license" for more information.
    >>> import shapefile
    >>> r = shapefile.Reader("NYC_MUSEUMS_GEO")
    >>> w = shapefile.Writer(r.shapeType)
    >>> w.fields = list(r.fields)
    >>> w.records.extend(r.records())
    >>> len(w.records)
    130
    

    您使用的pythonpyshp 版本是否与我使用的匹配?如果没有,您能否更新您的问题以包含您的环境的具体细节?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-24
      • 1970-01-01
      • 1970-01-01
      • 2011-05-01
      • 1970-01-01
      相关资源
      最近更新 更多