pyshp使用笔记

读取shapefile文件,添加新字段,打开TXT,遍历shapefile属性表和txt,如果属性表中某字段的值与txt中的某个值相同,则写入txt中的值到shapefile属性表,并生成新的shapefile文件

# -*- coding: utf-8 -*-
import os, time
import shapefile
from osgeo import ogr

def poi_editon(in_fc, out_fc, in_txt):
    print("------执行poi_editon-------")
    out_fc = os.path.join(os.path.dirname(in_fc), (os.path.basename(in_fc)[0:-4] + "_emtp.shp"))
    sf = shapefile.Reader(in_fc, encoding="utf-8", errors='ignore', encodingErrors="replace")
    w = shapefile.Writer(out_fc, shapeType=sf.shapeType, autoBalance=True, errors='ignore', encoding="GBK", encodingErrors="replace")
    # print(sf)
    fields = sf.fields[1:]
    # print(fields)
    w.fields = fields  # 添加原有字段
    # 添加新字段
    for i in [('Gate', 'C', 1), ('KindN', 'C', 6), ('Name_1', 'C', 254), ('Level', 'C', 2)]:  # 添加字段
        if i[0] not in [name[0] for name in fields]:
            w.field(*i)
    # w.field('Gate', 'C', size=1)
    for shapeRec in sf.iterShapeRecords():
        # print(*shapeRec.record)
        # w.record(*shapeRec.record)
        # w.shape(shapeRec.shape)
        with open(in_txt, "r", encoding="utf-8") as f:
            data = f.readlines()
            # print(data)
            for i in data:
                if i.endswith("\n"):  # 去除换行符
                    i = i[0:-1]
                if str(shapeRec.record[1]) == i[0:4] and i[(i.find(">") + 2):(i.find(">") + 3)] != " ":
                    shapeRec.record.append("")  # 'Gate'字段属性赋值为“”空值
                    shapeRec.record.append(i[(i.find(">") + 2):14])  # 'KindN'赋值
                    shapeRec.record.append(i[14:].strip())  # 'Name_1'赋值
                    # print("1")
                    # print(shapeRec.record)
        w.record(*shapeRec.record)
        w.shape(shapeRec.shape)
    w.close()
    sf.close()
def level_edition(in_fc, out_fc, in_level):
    print("------执行level_edition-------")
    in_fc = os.path.join(os.path.dirname(in_fc), (os.path.basename(in_fc)[0:-4] + "_emtp.shp"))
    sf = shapefile.Reader(in_fc, encoding="GBK", errors='ignore', encodingErrors="replace")
    w = shapefile.Writer(out_fc, shapeType=sf.shapeType, autoBalance=True, encoding="GBK", errors='ignore', encodingErrors="replace")
    # print(sf)
    fields = sf.fields[1:]
    # print(fields)
    w.fields = fields  # 添加原有字段
    for shapeRec in sf.iterShapeRecords():
        # print(*shapeRec.record)
        # w.record(*shapeRec.record)
        # w.shape(shapeRec.shape)
        with open(in_level, "r", encoding="utf-8") as f:
            data = f.readlines()
            # print(data)
            for i in data:
                if i.endswith("\n"):  # 去除换行符
                    i = i[0:-1]
                if i[:4] == "Kind":
                    continue
                if str(shapeRec.record[5]) == i[0:6]:
                    # print(shapeRec.record)
                    shapeRec.record[-1] = i[6:].strip()[0:2]  # 'level'赋值
                    # print("1")
                    # print(shapeRec.record)
        w.record(*shapeRec.record)
        w.shape(shapeRec.shape)
    w.close()
    sf.close()
    if os.path.exists(in_fc):
        driver = ogr.GetDriverByName('ESRI Shapefile')
        driver.DeleteDataSource(in_fc)



if __name__ == '__main__':
    start_time = time.time()
    in_fc = r"D:\台湾数据\gis_osm_pois_free_1.shp"
    in_txt = r"D:\台湾数据\poi_code2kindn.txt"
    in_level = r"D:\台湾数据\level.txt"
    out_fc = r"D:\台湾数据\gis_osm_pois_free_2.shp"
    poi_editon(in_fc, out_fc, in_txt)
    level_edition(in_fc, out_fc, in_level)
    total_time = time.time() - start_time
    print("耗时:%0.2f 秒" %total_time)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值