I know that you can quickly access the active layer with layer = iface.activeLayer()

Currently I'm working with multiple files in a Python script and my current method of accessing layer extents is this:

layer_file = "/path/to/file"
layer_meta = QFileInfo(layer_file)
layer_title = layer_meta.baseName()
layer = QgsRasterLayer(layer_file, layer_title)


I'm just wondering if anyone knows a more efficient way to access the extents of a file without having to reproduce these four lines of code for each file

1 Answer 1


Not sure there is a shorter code solution but you can refactor your code to use a function like below to avoid repeating the 4 lines everywhere

def get_layer_extent(filepath):
    layer_meta = QFileInfo(filepath)
    layer = QgsRasterLayer(filepath, layer_meta.baseName())
    return layer.extent()

paths = ["/path/to/file1", "/path/to/file2", "/path/to/file3"]

for layer_path in paths:
  • Great answer thanks!
    – Rob
    May 1, 2020 at 18:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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