1

I have the following data in a csv file('file.csv')

Date_Time,Latitude,Longitude,Wind_Speed,Status

09-10-2013/1130,13,93,50-60 gusting to 70,Observed

09-10-2013/2330,13.501,92.501,70-80 gusting to 90,Observed

I am able to convert the above data into a point shapefile using the pyshp module with the following code

import csv, shapefile
point = shapefile.Writer(shapefile.POINT)    
with open('file.csv', 'rb') as csvfile:
     csvreader = csv.DictReader(csvfile)
     header = csvreader.fieldnames
     for field in header:
         points.field(field) ## I could define the fields on the go in a loop
         for row in csvreader:
            parts.append([(float(row['Longitude'])), float(row['Latitude'])])
            points.point((float(row['Longitude'])),float(row['Latitude']))
            points.record(row['Date_Time'], row['Latitude'], row['Longitude'], row['Wind_Speed'], row['Status'])
            # for writing records each record has to be specified
points.save('points')

I would like to automate the record part i.e., point.record(row['Longitude'], row['Latitude'], row['Date_Time'],... so if the no.of fields are more writing each field name in "point.record(...)" can be automated.

0

In fact you are getting fields and records of CSV file through csv.DictReader, which is going to be the fields and records of DBF file. It gives you great flexibility and the best way to utilise this variable is to use both creating fields (be aware using default type and length here as you did) and saving the records as given below:

import csv, shapefile
points = shapefile.Writer(shapefile.POINT)
with open("file.csv", 'rb') as csvfile:
     csvreader = csv.DictReader(csvfile)
     header = csvreader.fieldnames
     [points.field(field) for field in header] #The first trick
     for row in csvreader:
        #parts.append([(float(row['Longitude'])), float(row['Latitude'])])
        points.point((float(row['Longitude'])),float(row['Latitude']))
        points.record(*tuple([row[f] for f in header])) #The second trick
points.save('points')

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.