1

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

George
  • 31
  • 1
  • 4
  • what should be the output? – gsb22 Jan 21 '21 at 10:43
  • The output must be a shapefile that contains points that represent the location of each city. The attributes of each city must be also contained in the shapefile. – George Jan 21 '21 at 15:04

1 Answers1

1

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

Younes
  • 391
  • 2
  • 9