CSV文件转Shp文件


准备工作

环境:Python3.7,需要引入shapefile、csv两个库
开发工具:Pycharm
示例文件:链接:
https://pan.baidu.com/s/16xbjqLMaTiVy2hB8FGUh4w
提取码:ch2d

原始教程网站(Pyshp文档):https://pypi.org/project/pyshp/


代码实现

import shapefile
import csv

# 读取文件的路径
readPath = r"示例文件的路径\Taxi_105 - trace.csv"

# 要写入新的文件存放路径
writeFilePath = r"你想输出的路径\CSVToShp.shp"

def readPointsCSV(readPath):
    with open(readPath) as myFile:
        myReader = csv.reader(myFile)
        i = 0
        for row in myReader:
            if i == 0:
                fields = row
                print(fields)
            if i>10:
                break
            # 此时输出的是一行行的列表
            # print(row)
            # print('+'.join(row))
            i=i+1
    return fields,myReader

'''CSV转ShapeFile'''
if __name__ == '__main__':
    print()

    # 写入文件的操作,并且是以线的方式
    w = shapefile.Writer(writeFilePath)
    # fields = readPointsCSV(readPath)
    with open(readPath) as myFile:
        myReader = csv.reader(myFile)
        i = 0
        for row in myReader:
            if i == 0:
                w.field(row[0],"N")
                w.field(row[1], "C")
                w.field(row[2], "F")
                w.field(row[3], "F")
                w.field(row[4], "N")
                w.field(row[5], "N")
                w.field(row[6], "N")
                # print(row)
                # w.fields = row
            else:
                # print(*row)
                # print(row[2],row[3])
                w.point(float(row[2]), float(row[3]))
                w.record(*row)

                # print(' '.join(row))
            i = i + 1



    # 激活自动平衡功能
    w.autoBalance = 1
    # 关闭写操作
    w.close()

说明

其中,w.field()需要说明每个字段的类型,并且有4个参数。第一个参数就是字段名字,第二个参数是类型(即C或N、D),第三个是限制长度,第四个是decimal。自己参考源代码或者官方文档吧。

C:字符串
N:正数或小数
D:时间类型

转载自:https://blog.csdn.net/Feng512275/article/details/88684308

You may also like...