George
George

Reputation: 41

convert text file to shapefile with python

I have a txt file that contains 5 columns(ID number,city,latitude,longitude,altitude) with tab delimiters. I want to convert this txt file into a shapefile format with python. I am a beginner in python and i do not know how to do this. Can anyone help me?

Thanks in advance

Upvotes: 1

Views: 1146

Answers (1)

Younes
Younes

Reputation: 421

There is a library to do this :

pip install pyshp

the import statement:

import shapefile

Now read your text file with something like:

w = shapefile.Writer(shapefile.POINT) #shapefile writer
filepath = 'yourfile.txt' #path to your text file
Lines[]=open(filepath).readlines() # read all the lines of your file
i=0 #index to help us get the headers
for line in Lines: 
   if i==0:
       i+=1
       for j in range len(line.split(";")):
           w.field('field{0}'.format(j)) #get the headers and stock them as fields
   
    w.point(line.split(";")[2],line.split(";")[3],line.split(";")[4]) #create points from last three columns
    w.record(field0=line.split(";")[0],field1=line.split(";")[1]) #add the fields you want to record in the file

w.save('outputshapefile') #write to a shapefile

Disclaimer! code not tested just to give you an idea, you can find more documentation Here

Upvotes: 1

Related Questions