解决Python CSV转GeoJSON时循环迭代覆盖旧条目问题
问题:CSV转GeoJSON时所有条目被最后一条数据覆盖
我用一段Python循环尝试将CSV文件转换为GeoJSON格式,脚本代码如下:
def make_json(csvFilePath, jsonFilePath): # create a dictionary data = { "type": "FeatureCollection", "features": [] } feature = { "type": "Feature", "geometry": { "type": "Point", "coordinates": [] }, "properties": {} } # Open a csv reader called DictReader with open(csvFilePath, encoding='utf-8') as csvf: csvReader = csv.DictReader(csvf) # Convert each row into a dictionary # and add it to data for rows in csvReader: feature['geometry']['coordinates'] = [float(rows['s_dec']),float(rows['s_ra'])] feature['properties'] = rows data['features'].append(feature) # Open a json writer, and use the json.dumps() # function to dump data with open(jsonFilePath, 'w', encoding='utf-8') as jsonf: jsonf.write(json.dumps(data, indent=4))
运行后出现新条目覆盖旧条目的问题,所有feature内容都和最后一条数据一致,输出内容如下:
{ "type": "FeatureCollection", "features": [ { "type": "Feature", "geometry": { "type": "Point", "coordinates": [ -67.33190277777777, 82.68714791666666 ] }, "properties": { "dataproduct_type": "image", "s_ra": "82.68714791666666", "s_dec": "-67.33190277777777", "t_min": "59687.56540044768", "t_max": "59687.5702465162", "s_region": "POLYGON 82.746588309 -67.328433557 82.78394862 -67.338513769" } }, { "type": "Feature", "geometry": { "type": "Point", "coordinates": [ -67.33190277777777, 82.68714791666666 ] }, "properties": { "dataproduct_type": "image", "s_ra": "82.68714791666666", "s_dec": "-67.33190277777777", "t_min": "59687.56540044768", "t_max": "59687.5702465162", "s_region": "POLYGON 82.746588309 -67.328433557 82.78394862 -67.338513769" } } ]}
问题原因
你在循环外部只创建了一个feature字典对象,每次循环修改它的属性并添加到features列表时,实际上是把同一个字典的引用重复添加到列表里。所有列表元素指向的都是同一个内存对象,每次循环修改的都是这个对象的内容,最终所有条目都会被最后一次修改的结果覆盖。
修正后的代码
把feature的定义移到循环内部,每次迭代都创建一个新的字典对象,确保每个feature都是独立的:
import csv import json def make_json(csvFilePath, jsonFilePath): # create a dictionary data = { "type": "FeatureCollection", "features": [] } # Open a csv reader called DictReader with open(csvFilePath, encoding='utf-8') as csvf: csvReader = csv.DictReader(csvf) # Convert each row into a dictionary # and add it to data for rows in csvReader: # 每次循环创建新的feature对象 feature = { "type": "Feature", "geometry": { "type": "Point", "coordinates": [] }, "properties": {} } feature['geometry']['coordinates'] = [float(rows['s_dec']),float(rows['s_ra'])] feature['properties'] = rows data['features'].append(feature) # Open a json writer, and use the json.dumps() # function to dump data with open(jsonFilePath, 'w', encoding='utf-8') as jsonf: jsonf.write(json.dumps(data, indent=4))
内容的提问来源于stack exchange,提问作者thefreeline
相关产品推荐
相关产品推荐

