3

I transform a csv file into a shapefile using the following script:

import shapefile as shp  
import csv            
import tkinter.filedialog   
import urllib.request    
import os 
a = 'csvFiletoTransform.csv'


filename = 'C:/TEMP/ToscaAuxiliar.csv'
urllib.request.urlretrieve(a,filename)    

out_file = tkinter.filedialog.asksaveasfilename()

nombre,codigo,y,x,time=[],[],[],[],[] 


with open('C:/TEMP/xxxx.csv', 'r') as csvfile:
    r = csv.reader(csvfile, delimiter=',')
    for i,row in enumerate(r):
        if i > 0: #skip header
           nombre.append(row[0])
           codigo.append(row[1])
           y.append(float(row[2]))
           x.append(float(row[3]))
           time.append(str(row[4])) 


w = shp.Writer(shp.POINT)
w.autoBalance = 1 #ensures gemoetry and attributes match
w.field('Longitud','F',10,8)
w.field('Latitud','F',10,8)
w.field('Date','D')
w.field('Date / Time','C',50)
w.field('ID','N')

for j,k in enumerate(x):
   w.point(k,y[j]) #write the geometry
   w.record(k,y[j],codigo[j], time[j], nombre[j]) 

os.remove('C:/TEMP/xxxx.csv') 
 w.save(out_file)

it works, but the .prj file is lost.

It creates only the .dbf .shp & .shx files.

How can I do to create the prj file also ?

nmtoken
  • 13,355
  • 5
  • 38
  • 87
kamome
  • 757
  • 2
  • 12
  • 25

2 Answers2

1

For reading csv files, it is easier to use csv:DictReader (or pandas with pandas.read_csv).

from csv import DictReader
reader = DictReader(open("xxxx.csv"), delimiter=',')

The result is a Python dictionary with the values in the first row used as the fieldnames/keys

Example

reader = DictReader(open("my.csv"), delimiter=',')
for row in reader:
    print row

{'y': '89857.66933', 'x': '205552.62867', 'z': '222.2'}
{'y': '89117.14521', 'x': '203039.279', 'z': '232.18'}
{'y': '89312.90303', 'x': '205228.00325', 'z': '216.11'}
{'y': '88530.96348', 'x': '203384.44062', 'z': '213.41'}
{'y': '89202.89231', 'x': '204949.65734', 'z': '226.02'}

And you only need one loop (and not two) to create the shapefile (you can also use Fiona as in GitHub Gist: gistfile1.py of Sean Gillies)

import shapefile as shp  
filename = 'test'
w = shp.Writer(shp.POINT)
w.field('Longitud','F',10,8)
w.field('Latitud','F',10,8)
w.field('altitud','F',10,8)
reader = DictReader(open("my.csv"), delimiter=',')
# writing shapefile
for i in reader:
    w.point(float(i['x']),float(i['y']))
    w.record(float(i['x']),float(i['y']),float(i['z']))
w.save(filename)

now write the prj file (Pyshp: Creating a .prj file):

# writing prj file
prj = open("%s.prj" % filename, "w")
epsg = 'PROJCS["Belge 1972 / Belgian Lambert 72",GEOGCS["Belge 1972",DATUM["D_Belge_1972",SPHEROID["International_1924",6378388.0,297.0]],PRIMEM["Greenwich",0.0],UNIT["Degree",0.017453292519943295]],PROJECTION["Lambert_Conformal_Conic"],PARAMETER["central_meridian",4.367486666666666],PARAMETER["latitude_of_origin",90.0],PARAMETER["standard_parallel_1",51.166667233333335],PARAMETER["false_easting",150000.013],PARAMETER["false_northing",5400088.438],PARAMETER["standard_parallel_2",49.83333389999999],UNIT["m",1.0]]'
prj.write(epsg)
prj.close()

Control of the resulting shapefile with Fiona

 import fiona
 # read the shapefile
 c = fiona.open('test.shp')
 # schema of the shapefile
 c.schema
 {'geometry': 'Point', 'properties': OrderedDict([(u'Longitud', 'float:10.8'), (u'Latitud', 'float:10.8'), (u'altitud', 'float:10.8')])}
 # crs of the shapefile
 c.crs
  {u'lon_0': 4.367486666666666, u'ellps': u'intl', u'y_0': 5400088.438, u'no_defs': True, u'proj': u'lcc', u'x_0': 150000.013, u'units': u'm', u'lat_2': 49.83333389999999, u'lat_1': 51.16666723333334, u'lat_0': 90}
 # first feature
 c.next()
 {'geometry': {'type': 'Point', 'coordinates': (205552.62867, 89857.66933)}, 'type': 'Feature', 'id': '0', 'properties': OrderedDict([(u'Longitud', 205552.628), (u'Latitud', 89857.6693), (u'altitud', 222.2)])}

.

gene
  • 54,868
  • 3
  • 110
  • 187
0

You could try with ogr like this

from osgeo import ogr

driver = ogr.GetDriverByName("CSV")
datasource = driver.Open("path\to\csv.csv")
for i in range(datasource.GetLayerCount()):
    layer = datasource.GetLayer(i)
    srcSpatialRef = layer.GetSpatialRef()
    srs_wkt = srcSpatialRef.ExportToWkt()

#save the srs_wkt into shapefile.prj
Below the Radar
  • 3,593
  • 1
  • 31
  • 58