[GIS] glob.glob and gdal_translate not working

gdalpython

I have a problem with my python script. I wrote it to convert MODIS data from .hdf into .tif. It will convert all files in a folder using a loop. I do not know which command I must enter to assume the files from the folder as input file. I tried *.hdf but then I got errors indicating that the file doesn´t exist.

The output-name of the new .tif should be the input name of the .hdf. At this point in my script it doesn´t work for me. I have no idea what I have to write now in the "gdal_translate"-command. I tried it with *.tif but this doesn't work.

#!/usr/bin/python

import os
import glob
from osgeo import gdal
from osgeo import ogr 
from osgeo import osr 
from osgeo import gdal_array 
from osgeo import gdalconst 
from osgeo.gdalconst import *

path = ''
path = raw_input('Directory? (z.B. C:\Daten\Modis\):')

# change to path
os.chdir( path )

# checks directory
vcheck = os.getcwd()

file = glob.glob('*.hdf')

for file in glob.glob('*.hdf'):

os.system('gdal_translate -of GTiff -a_srs EPSG:4326 "HDF4_EOS:EOS_GRID:"*.hdf":MODIS_Grid_8Day_Fire:FireMask" *.tif')

Best Answer

There were a few issues in the script. If you're new to Python I'd strongly recommend the Python tutorial and starting there.

The big issue was that it appears that you're trying to set your input and output filenames to a wildcard (the *.tif).

Additionally since you're running GDAL from the command prompt through os.system you don't need to import the osgeo libraries (but make sure that the GDAL bin directory is on your system PATH).

Lastly, file is a built in type, so it's not a good idea to use it as a variable name.

Instead try the following using string formatting operations:

#!/usr/bin/python

import os
import os.path
import glob

path = raw_input('Directory? (z.B. C:\Daten\Modis\):')

# change to path
os.chdir( path )

for f in glob.glob('*.hdf'):
    os.system('gdal_translate -of GTiff -a_srs EPSG:4326 "HDF4_EOS:EOS_GRID:%s:MODIS_Grid_8Day_Fire:FireMask" %s.tif' % (f, os.path.basename(f)))
Related Question