4

I am new of programming and I need help for it. I would use gdal_edit to modify SRC of 300 hundred aerial photos, if I use this tool one by one work perfectly, but I would want to use it in a cycle in a python script to simplify and get faster my job.

This is the tool I used:

gdal_edit -a_srs EPSG:3004 "C:/Users/Laptop/Desktop/test/img.ecw"   

While this is the python script in that I would use this tool:

import os, gdal

dir="C:/Users/Laptop/Desktop/test"
array=os.listdir(dir)
for e in array:
    if os.path.splitext(e)[1]==".ecw":
        print(e)
        gdal_edit -a_srs EPSG:3004 dir+e

How can I use gdal_edit in this code? I use OsGeo4W Shell that has gdal and python preinstallated.

3
  • One way is to create a string that matches exactly what you would type normally, then use subprocess.call(string) to execute it. You will need to import subprocess module. Also, I have noticed that it is best to create your string as a list, i.e. string = ['gdal_edit', '-a_srs', 'EPSG:3004', 'C:/Users/Laptop/Desktop/test/img.ecw']
    – Jon
    Oct 4, 2017 at 20:46
  • Hi Jon, thank you for your post, I tried using your advice before in direct command: import subprocess subprocess.call['gdal_edit', '-a_srs', 'EPSG:3004', 'C:/Users/SIGEO/Documents/Luca/temp/test/521142.ecw'] but this is been error answer: Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'function' object has no attribute 'getitem' Can you understand it? Oct 5, 2017 at 9:02
  • If you're using the exact code you posted, you have to call subprocess.call with (), not with []. Break it up as I suggested in my first comment: string = ['gdal_edit'...etc] then subprocess.call(string). It's more readable, and, as you discovered, less prone to mistakes. If you want to use your one-liner, just wrap your list in (); i.e. subprocess.call(['gdal_edit', '-a_srs', 'EPSG:3004', 'C:/Users/SIGEO/Documents/Luca/temp/test/521142.ecw'])
    – Jon
    Oct 5, 2017 at 15:08

1 Answer 1

4

The gdal_edit program is written in Python. You can copy a few lines of its code into your loop over the names of files to modify. This approach will be much faster than executing gdal_edit in a subprocess because creating new processes and launching Python takes a significant amount of time.

Here's how it opens the dataset for editing: https://github.com/OSGeo/gdal/blob/master/gdal/swig/python/scripts/gdal_edit.py#L280.

Here's how it updates the dataset's spatial reference system: https://github.com/OSGeo/gdal/blob/master/gdal/swig/python/scripts/gdal_edit.py#L310-L319.

1
  • 2
    Links are broken now, due to migration
    – mr.tarsa
    Jan 18, 2022 at 20:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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