3

I have a path of a raster layer. I want to get name of this layer in GDAL. In below code I want to get aa.tif

from osgeo import gdal

dataset = gdal.Open("/Data/raster/aa.tif")
print dataset.GetName()

But I received below error:

Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "/tmp/tmpq3Peqi.py", line 5, in <module>
    print dataset.GetName()
  File "/usr/lib/python2.7/dist-packages/osgeo/gdal.py", line 1804, in <lambda>
    __getattr__ = lambda self, name: _swig_getattr(self, Dataset, name)
  File "/usr/lib/python2.7/dist-packages/osgeo/gdal.py", line 74, in _swig_getattr
    return _swig_getattr_nondynamic(self, class_type, name, 0)
  File "/usr/lib/python2.7/dist-packages/osgeo/gdal.py", line 69, in _swig_getattr_nondynamic
    return object.__getattr__(self, name)
AttributeError: type object 'object' has no attribute '__getattr__'

How can I do it?

3
  • Where's the documentation for "GetName()"? Or was that a guess, because there's a GetName for ogr data sources? Can't you keep the filename somewhere and get the name part from that?
    – Spacedman
    Oct 30, 2017 at 8:09
  • Hi @Spacedman, Your're right. `GetName' is not for gdal data sources. No unfortunately in my long code I receive a list of path raster layers and for next steps need only raster layer names.
    – HMadadi
    Oct 30, 2017 at 8:13
  • You mean "a list of paths of raster layers"?
    – Spacedman
    Oct 30, 2017 at 10:02

2 Answers 2

5

GetDescription returns the full path:

>>> import osgeo
>>> from osgeo import gdal
>>> d = gdal.Open("./swb/srtm_38_04.tif")
>>> d.GetDescription()
'./swb/srtm_38_04.tif'
>>> 

then use standard python path munging tools to get the name.

4
  • Sorry I think I couldn't ask clearly my question. For example In your code I have './swb/srtm_38_04.tif' fullpath, In fact I want only srtm_38_04.tif or srtm_38_04.
    – HMadadi
    Oct 30, 2017 at 8:36
  • You may also try d.GetMetadata('DERIVED_SUBDATASETS') but it will return full path to. You have to use os.path.basename to get file name from path. Oct 30, 2017 at 10:00
  • @nickan that's what I meant by "standard python path munging tools", like os.path.split, as mentioned in the accepted answer. Your question made it seem like you wanted the path from a GDAL Dataset object.
    – Spacedman
    Oct 30, 2017 at 10:03
  • @Spacedman, you 're right. It was better I asked my question in other place, but because I used gdal in my code I thought it ask here, sorry.
    – HMadadi
    Oct 30, 2017 at 12:59
1

You don't need Gdal for that. Check out os.path and the following link: https://stackoverflow.com/questions/7304117/split-filenames-with-python#7304165.

0

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.