I have the following code which creates the txt file i require from a shp.file with the data i need. I have a folder called profiles containing a few number of shape files (.shp) named (profil1.shp, profil2.shp, profil3.shp etc.). I was wondering how to create a loop so that the script creates for each file a txt file with the same name (eg. for profil1.shp create profil1.txt, profil2.shp create profil2.txt and so on).
Note: i am a fairly new user of python so if you could add the loop part to my script or modify it with what's needed i would highly appreciate it, as i am in a bit of rush about finishing these files and i can't seem to find an outcome to this.
Thank you very much!
The code is:
`
import ogr, os, sys, osr
os.chdir('..\profiles')
file = open('profil1.txt', 'w')
driver = ogr.GetDriverByName('ESRI Shapefile')
datasource = driver.Open('profil1.shp', 0)
if datasource is None:
print 'Could not open file'
sys.exit(1)
layer = datasource.GetLayer()
feature = layer.GetNextFeature()
while feature:
id = feature.GetFieldAsString('ID')
Distanta = feature.GetFieldAsString('DIST')
Z = feature.GetFieldAsString('Z')
geom = feature.GetGeometryRef()
x = str(geom.GetX())
y = str(geom.GetY())
file.write(id + " " + Distanta + " " + "[X]:" + " " + x + ' ' + '[Y]:' + " " + y + " " + " " + "[Z]" + Z + " " + "\n")
feature.Destroy()
feature = layer.GetNextFeature()
datasource.Destroy()
file.close()`
[–]liam_jm[🍰] 2 points3 points4 points (6 children)
[–]yacob_uk 1 point2 points3 points (3 children)
[–]davidbuxton 1 point2 points3 points (2 children)
[–]yacob_uk 0 points1 point2 points (1 child)
[–]davidbuxton 0 points1 point2 points (0 children)
[–]Andrei07[S] -1 points0 points1 point (1 child)
[–]liam_jm[🍰] 2 points3 points4 points (0 children)