【问题标题】:Python: for loop stops at first row when reading from csvPython:从csv读取时,for循环在第一行停止
【发布时间】:2016-02-12 16:57:18
【问题描述】:

使用此代码,我可以让它通过 csv 中的第一行触发并发布内容。如果没有 for 循环,它也可以很好地工作。我还使用简单的打印语句,能够打印出 csv 中的所有行。我遇到困难的地方是如何让它循环通过我的 csv(2300 行)并替换两个内联变量。我已经尝试了几次迭代,移动语句等,这是我的最新尝试。

from __future__ import print_function
import arcrest
import json
import csv
if __name__ == "__main__":
    username = "uid"
    password = "pwd"
    portalId = "id"
    url = "http://www.arcgis.com/"
    thumbnail_url = ""
with open('TILES.csv') as csvfile:
    inputFile = csv.DictReader(csvfile)
    x = 0 # counter to display file count
    for row in inputFile:
        if x == 0:
            map_json = {
  "operationalLayers": [
    {
      "templateUrl": "https://{subDomain}.tiles.mapbox.com/v4/abc.GRSM_"+row['ID']+"_pink/{level}/{col}/{row}.png?access_token=pk.secret",
      "id": "GRSM_SPECIES_OBSERVATIONS_MAXENT_5733",
      "type": "WebTiledLayer",
      "layerType": "WebTiledLayer",
      "title": row['Species']+" Prediction",
      "copyright": "GRSM",
      "fullExtent": {
        "xmin": -20037508.342787,
        "ymin": -20037508.34278,
        "xmax": 20037508.34278,
        "ymax": 20037508.342787,
        "spatialReference": {
          "wkid": 102100
        }
      },
      "subDomains": [
        "a",
        "b",
        "c",
        "d"
      ],
      "visibility": True,
      "opacity": 1
    }
  ],
  "baseMap": {
    "baseMapLayers": [
      {
        "id": "defaultBasemap",
        "layerType": "ArcGISTiledMapServiceLayer",
        "opacity": 1,
        "visibility": True,
        "url": "http://services.arcgisonline.com/ArcGIS/rest/services/World_Topo_Map/MapServer"
      }
    ],
    "title": "Topographic"
  },
  "spatialReference": {
    "wkid": 102100,
    "latestWkid": 3857
  },
  "version": "2.0"
}
    securityHandler = arcrest.AGOLTokenSecurityHandler(username,
                                                       password)
    #   Create the administration connection
    #
    admin = arcrest.manageorg.Administration(url, securityHandler)
    #   Access the content properties to add the item
    #
    content = admin.content
    #   Get the user    #
    user = content.users.user()
    #   Provide the item parameters
    #
    itemParams = arcrest.manageorg.ItemParameter()
    itemParams.title = "GRSM_"+row['Species']
    itemParams.thumbnailurl = ""
    itemParams.type = "Web Map"
    itemParams.snippet = "Maxent Output: "+row['Species']
    itemParams.licenseInfo = "License"
    itemParams.accessInformation = "Credits"
    itemParams.tags = "Maxent"+row['Species']
    itemParams.description = "This map depicts the tiled output of a Maxent model depicting the probability of occurrence of "+row['Species']+". An in-line legend is not available for this map. "
    itemParams.extent = "-84.1076,35.2814,-82.9795, 35.8366"

    #   Add the Web Map
    #
    print (user.addItem(itemParameters=itemParams,
                              overwrite=True,
                              text=json.dumps(row)))
    x = x + 1

这是 csv:

Species,ID
Abacion_magnum,0000166
Abaeis_nicippe,0000169
Abagrotis_alternata,0000172
Abies_fraseri,0000214
Ablabesmyia_mallochi,0000223
Abrostola_ovalis,0000232
Acalypha_rhomboidea,0000253
Acanthostigma_filiforme,0000296
Acanthostigma_minutum,0000297
Acanthostigma_multiseptatum,0000298
Acentrella_ampla,0000314
Acer_negundo,0000330
Acer_pensylvanicum,0000333
Acer_rubrum_v_rubrum,0000337
Acer_rubrum_v_trilobum,0000338
Acer_saccharum,0000341
Acer_spicatum,0000343

【问题讨论】:

  • 调试问题应该有一个minimal reproducible example。在这种情况下,如果您可以删除与特定错误无关的代码,则更容易找出问题所在。
  • 现在,将 x==0 更改为 true。由于它只适用于第一个循环,我的猜测是这个 if 语句阻止了其余的行被处理。
  • 注意:我建议您将文件打开为with open('TILES.csv', 'rb') as csvfile:
  • @Martin Evans,做到了,感谢您的提示(但并没有让我通过第一次迭代).....
  • securityHandler = arcrest.AGOLTokenSecurityHandler(username, password) 在你的 for 循环之外。你是故意的吗?

标签: python for-loop gis mapbox arcgis


【解决方案1】:

我认为你的缩进是错误的,你只有在 for 循环 if 和 json:

 if x == 0:
      map_json = {
  "operationalLayers": [
    {
      "templateUrl": "https://{subDomain}.tiles.mapbox.com/v4/abc.GRSM_"+row['ID']+"_pink/{level}/{col}/{row}.png?access_token=pk.secret",
      "id": "GRSM_SPECIES_OBSERVATIONS_MAXENT_5733",
      "type": "WebTiledLayer",
      "layerType": "WebTiledLayer",
      "title": row['Species']+" Prediction",
      "copyright": "GRSM",
      "fullExtent": {
        "xmin": -20037508.342787,
        "ymin": -20037508.34278,
        "xmax": 20037508.34278,
        "ymax": 20037508.342787,
        "spatialReference": {
          "wkid": 102100
        }
      },
      "subDomains": [
        "a",
        "b",
        "c",
        "d"
      ],
      "visibility": True,
      "opacity": 1
    }
  ],
  "baseMap": {
    "baseMapLayers": [
      {
        "id": "defaultBasemap",
        "layerType": "ArcGISTiledMapServiceLayer",
        "opacity": 1,
        "visibility": True,
        "url": "http://services.arcgisonline.com/ArcGIS/rest/services/World_Topo_Map/MapServer"
      }
    ],
    "title": "Topographic"
  },
  "spatialReference": {
    "wkid": 102100,
    "latestWkid": 3857
  },
  "version": "2.0"
}

【讨论】:

  • 最终,这是一个与 JSON 格式混淆缩进有关的令人心碎的问题,通过 notepad++ 和查找/替换空格的制表符解决。
【解决方案2】:

您可能只在结果中得到一行的原因是因为您将代码包含在条件为 x == 0 的 if 语句中。我可以看到您在 for 循环之外将 x 设置为 0 并且在循环结束时,您将增加 x。这导致 x 不再等于 0,因此您的 if 语句条件为假。

尝试完全删除 if 语句和末尾的增量行。 只需使用:

for row in inputFile:
    # your code here

这将允许您循环浏览 csv 文件

【讨论】:

  • 感谢您指出这一点......但没有骰子。仍然通过一次迭代成功触发...删除 x = 0 # 计数器以显示文件计数,如果 x == 0: 和 x = x + 1
猜你喜欢
  • 2012-03-05
  • 1970-01-01
  • 2019-01-11
  • 2018-08-18
  • 2017-03-19
相关资源
最近更新 更多