将 CSV 转换为 GeoJSON 的 Python 脚本

标签 python json csv geojson

我需要一个 Python 脚本来将 CSV 数据转换为 GeoJSON 输出。输出应符合以下格式:

{
  "type": "FeatureCollection",
  "features": [
    {
      "type": "Feature",
      "geometry": {
        "type": "Point",
        "coordinates":  [ -85.362709,40.466442 ]
      },
      "properties": {
        "weather":"Overcast",
        "temp":"30.2 F"
      }
    }
  ]
}

我正在使用这个脚本来运行该过程,但它没有产生所需的输出:

import csv, json
    li = []
    with open('CurrentObs.csv', newline='') as csvfile:
        reader = csv.reader(csvfile, delimiter=',')
        for latitude, longitude, weather, temp in reader:
            li.append({
               "latitude": latitude,
               "longitude": longitude,
               "weather": weather,
               "temp": temp,
               "geo": {
                    "__type": "GeoPoint",
                    "latitude": latitude,
                    "longitude": longitude,
                }
            })

    with open("GeoObs.json", "w") as f:
        json.dump(li, f)

非常感谢任何帮助!

最佳答案

可以直接使用 geojson 包:

import csv, json
from geojson import Feature, FeatureCollection, Point

features = []
with open('CurrentObs.csv', newline='') as csvfile:
    reader = csv.reader(csvfile, delimiter=',')
    for latitude, longitude, weather, temp in reader:
        latitude, longitude = map(float, (latitude, longitude))
        features.append(
            Feature(
                geometry = Point((longitude, latitude)),
                properties = {
                    'weather': weather,
                    'temp': temp
                }
            )
        )

collection = FeatureCollection(features)
with open("GeoObs.json", "w") as f:
    f.write('%s' % collection)

关于将 CSV 转换为 GeoJSON 的 Python 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48586647/

相关文章:

python - 使用 Python 将制表符分隔的 txt 文件转换为 csv 文件

python - 导入错误 : No module named - Python

python - 如何快速制作这种相等数组(在 numpy 中)?

Python:计算列表中的重复元素

Python json.loads 失败,出现 `ValueError: Invalid control character at: line 1 column 33 (char 33)`

Android HttpPost请求异常

android - Json 数组解析在 Android 中总是有 null 结果

csv - SonarQube 的自定义图表插件

Python 将 UTF8 字符串插入 SQLite

python - 将 CSV 文件拆分为多个(大小不同的)文件,保留标题