Search code examples
pythonogr

Script Loop through files in directory


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 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).

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()

edit: the code is returning a Could not open file.Photo of the folder containing the files and their respective names. Safe to assume I am doing something wrong.

import ogr, os, sys, osr,os.path
os.chdir = ('C:\Users\Andrei\Desktop\profil3')
l = os.listdir('C:\Users\Andrei\Desktop\profil3')
for i in l:
    if i.endswith('.shp'):
        s1 = s.split('.')[0] + '.txt'
        file = open(s1, 'w')

    driver = ogr.GetDriverByName('ESRI Shapefile')
    datasource = driver.Open(i, 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()

Solution

  • You can use os.listdir() to list the files and folders in the current directory. This returns a list of all files in the current directory (or the directory given to it as parameter , if no parameter is specified it checks the current directory) .

    Then you can check for files with the name ending with .shp using string.endswith() function and then use that to create your new files.

    Example of a small portion -

    import os , os.path
    l = os.listdir()
    for i in l:
        if i.endswith('.shp'):
            s1 = s.split('.')[0] + '.txt'
    

    At the end s1 would contain the file with extension as .txt .

    Then you can do your logic on this file, and keep on doing like this.

    Full code would look something like -

    import ogr, os, sys, osr,os.path

    os.chdir('..\profiles') l = os.listdir() for i in l: if i.endswith('.shp'): s1 = s.split('.')[0] + '.txt' file = open(s1, 'w')

        driver = ogr.GetDriverByName('ESRI Shapefile')
    
        datasource = driver.Open(i, 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()
    

    A better way of openning files, etc is using with statement. Look up its tutorial here.