Command line into shape file recording -csv

1, except for some necessary settings into shapefile file, python csv file read there are some caveats.

(1) first reads the first row of field names as fds

In this read data in the file contents after (2), this part of the code is relatively long

(3) code is error-prone place is ds = driver.CreateDataSource (filename [: - 4]) This line of code to generate the shapefile process, first given name to create the file folder (I have here is stations2), then shp file in the appropriate folder to store other documents, file name and the name of the sub-folders may be different, but attention must not be written as ds = driver.CreateDataSource (filename), or otherwise the original filename is the name of the csv file will be deleted. After successfully created a folder, you can create a layer, layer = ds.CreateLayer (filename [: -4], srs = spatialref, geom_type = geomtype, options = [ 'ENCODING = UTF-8']) This is a code prior has been an error, and later is how a good tune is not clear, but there is no path and no Chinese relations.

(4) The following code is written only x, y and precipitation

2、


##给定一个采样点文件(格式:csv) 将其转换为shape文本
from osgeo import ogr
from osgeo import osr
import os

#############read csv file############

filename='stations2.csv'
fh=open(filename,'r')

lns=fh.readline()
lns=lns.strip()
fds=lns.split(',')

data=[]

lns=fh.readline()
vals=[]
while lns is not None:
    lns=lns.strip()
    if len(lns)==0:
        break
    for v in lns.split(','):
        #print(v)
        v_ = float(v)
        vals.append(v_)
    data.append(vals)
    lns=fh.readline()
    vals=[]

fh.close()

############create shapefile#############

= ogr.GetDriverByName Driver ( "ESRI Shapefile")

# as the file already exists, delete
shapename = "stations2.shp"
IF os.access (shapename, os.F_OK):
    driver.DeleteDataSource (shapename)

# create Shape file
ds = driver.CreateDataSource (filename [: -. 4])

spatialRef = osr.SpatialReference ( 'LOCAL_CS [ "the arbitrary"]')
geomtype # = ogr.wkbPoint point layer

layer = ds.CreateLayer (filename [: -4 ], srs = spatialRef,

geom_type = geomtype,
                       Options = [ '= UTF-the eNCODING. 8']) # create layer, deposit number defined

data encoding

fd_x = ogr.FieldDefn (fds [0] , ogr.OFTReal) # float
fd_x. SetPrecision (. 3)
fd_y = ogr.FieldDefn (FDS [. 1], ogr.OFTReal) # float
fd_y.SetPrecision (. 3)
fd_p = ogr.FieldDefn (FDS [. 3], ogr.OFTReal) # float
fd_p.SetPrecision(3)

layer.CreateField(fd_x)
layer.CreateField(fd_y)
layer.CreateField(fd_p)
for i in range(len(data)):
    d=data[i]
    wkt="POINT(%f %f)"%(d[0],d[1])
    geom=ogr.CreateGeometryFromWkt(wkt)
    feat=ogr.Feature(layer.GetLayerDefn())#创建SF
    feat.SetGeometry(geom)
    feat.SetField(fds[0],d[0])
    feat.SetField(fds[1],d[1])
    feat.SetField(fds[3],d[3])
    layer.CreateFeature(feat)

ds.Destroy()

Guess you like

Origin www.cnblogs.com/vividautumn/p/11613118.html