Python文件格式转换

12 篇文章 1 订阅

 一.csv转geojson

1.将带有点坐标的 csv 转 geojson, 不带其他属性

"""
将带有点坐标的 csv 转 geojson, 不带其他属性
"""
import csv


csv_file = open('E:/test.csv', encoding='gbk')
csv_reader = csv.reader(csv_file)

geojson = '{"type":"FeatureCollection","features":['
for index, row in enumerate(csv_reader):
    print(row[0])
    geojson += '{"geometry":{"coordinates":[%f,%f],"type":"Point"},"properties":{},"type":"Feature"},' % (float(row[0]),float(row[1]))


geojson = geojson[:-1] + ']}'
links_file = open('test.geojson', 'w')
links_file.write(geojson)

2.将带有点坐标的 csv 转 geojson, 带其他属性

"""
将带有点坐标的 csv 转 geojson, 带其他属性
"""
import csv
import json

csv_file = open('test.csv', encoding='utf8')
csv_reader = csv.reader(csv_file)

geojson = '{"type":"FeatureCollection","features":['

lon_index = 0
lat_index = 1
for index, row in enumerate(csv_reader):
    if index == 0:
        header = row
        continue

    property_dict = {}
    for indexJ, j in enumerate(row):
        if indexJ == lon_index or indexJ == lat_index:
            continue
        property_dict[header[indexJ]] = j

    geojson += '{"geometry":{"coordinates":[%f,%f],"type":"Point"},"properties":%s,"type":"Feature"},' \
               % (float(row[lon_index]), float(row[lat_index]), json.dumps(property_dict, ensure_ascii=False))


geojson = geojson[:-1] + ']}'
links_file = open('test.geojson', 'w', encoding='utf8')
links_file.write(geojson)

二.geojson转geojson

geojson转geojson, 并加上一个随机数

"""
geojson转geojson, 并加上一个随机数
"""
import json
import random

file_object = open("D:/random_points.geojson", "r+", encoding='utf8')
file_data_str = file_object.read()
file_object.close()

origin_data = json.loads(file_data_str)

geojson = '{"type":"FeatureCollection","features":['
for i in origin_data["features"]:
    properties = i["properties"]
    properties["counts"] = random.randint(0, 20000)
    geojson += '{"geometry":{"coordinates":%s,"type":"Point"},"properties":%s,"type":"Feature"},' % (
        json.dumps(i["geometry"]["coordinates"]), json.dumps(i["properties"], ensure_ascii=False))

geojson = geojson[:-1] + ']}'
links_file = open('D:/random_points_value.geojson', 'w', encoding='utf8')
links_file.write(geojson)

三.csv转json

"""
将 csv 转为 json
"""
import csv
import json

csv_file = open('F:/test.csv', encoding='utf8')
csv_reader = csv.reader(csv_file)

list_data = []

header = []
for index, row in enumerate(csv_reader):
    if index == 0:
        header = row
    else:
        one_json = {}
        for index_j, j in enumerate(row):
            one_json[header[index_j]] = row[index_j]
        list_data.append(one_json)


json_data = {"data": list_data}

json_file = open('F:/test.json', 'w', encoding='utf8')
json_file.write(json.dumps(json_data, ensure_ascii=False))

 四.json转geojson

1.读取含有点坐标的json文件, 并转为geojson

"""
读取含有点坐标的json文件, 并转为geojson
"""
import json

file_object = open("D:/收费员位置高德.json", "r+", encoding='utf8')
file_data_str = file_object.read()
file_object.close()

origin_data = json.loads(file_data_str)

geojson = '{"type":"FeatureCollection","features":['
for i in origin_data["data"]:
    geojson += '{"geometry":{"coordinates":[%s,%s],"type":"Point"},"properties":{},"type":"Feature"},' % (
            i["longitude"], i["latitude"])

geojson = geojson[:-1] + ']}'
links_file = open('D:/收费员位置高德.geojson', 'w', encoding='utf8')
links_file.write(geojson)

2.逐行读取含有点坐标的json文件, 并逐行写入geojson

"""
逐行读取含有点坐标的json文件, 并逐行写入geojson中
"""
import json

json_str = ""
for line in open("E:/income_province_evsmc.json"):
    json_str += line

json_dict = json.loads(json_str)

file_writer = open("E:/points.geojson", "a+")

geojson = '{"type":"FeatureCollection","features":['
file_writer.write(geojson)
for index, i in enumerate(json_dict["result"]):

    coords = "%f,%f" % (i["lon"], i["lat"])
    file_writer.write('{"geometry": {"type": "Point", "coordinates": [%s]},"properties": {}}' % coords)

    if index != len(json_dict["result"]) - 1:
        file_writer.write(',')

file_writer.write(']}')

 五.文本符处理

1.读取csv,将换行符处理后再插入另一个csv

"""
读取csv,将换行符处理后再插入另一个csv
"""

import csv

csv_file = open("test.csv", encoding='utf-8')
csv_reader_lines = csv.reader(csv_file)

file_object = open("abc.csv", 'w', newline='', encoding='utf-8')
writer = csv.writer(file_object)

for index, i in enumerate(csv_reader_lines):
    i[4] = i[4].replace(" ", "").replace("\r", "").replace("\n", "")
    writer.writerow(i)

file_object.close()

2.去除txt文件中的各种转义符

"""
去除txt文件中的各种转义符
"""
read_object = open("polygon.geojson", "r+", encoding="utf8")
file_data_str = read_object.read()
read_object.close()


data_str = file_data_str.replace("\n", "").replace("\r", "").replace(" ", "").replace(" ", "")
txt_file = open("polygon_format.geojson", 'w', encoding="utf8")
txt_file.write(data_str)
txt_file.close()

  • 4
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

纯洁的小魔鬼

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值