2

I have several .qgz project in different directories. I would like to get all the (displayed) layer names from each project. I tried several forms of code to get it from documentation, but it only returns an empty list in each file.

for settlement in os.listdir(source):
    settlement_path = os.path.join(source, str(settlement))
    settlement_name = str(settlement)

    for qgz in os.listdir(settlement_path):
        if str(qgz).endswith('.qgz'):
            project = QgsProject.instance()
            project.read(str(qgz))
            layers_names = []

            for layer in project.mapLayers().values():
                layers_names.append(layer.name())
            print(layers_names)

        project.clear()
4
  • 1
    Have you made sure your path (qgz) is correct?
    – Bera
    Commented Nov 22, 2021 at 10:31
  • I printed out the files and also made a join for paths but the results are same. Commented Nov 22, 2021 at 11:41
  • did you try printing out project.mapLayers()?
    – Ian Turton
    Commented Nov 22, 2021 at 11:54
  • Returns empty dictionaries in each case. My qgzs for sure aren't empty. Commented Nov 22, 2021 at 11:58

1 Answer 1

3

You miss os.path.join in the second loop.

Change

project.read(str(qgz))

to

project.read(os.path.join(settlement_path, str(qgz)))
1
  • Wow It works! Funny, I tried joining in the second loop as a separate variable and it did not work but in this way it works perfectly. Thank you! Commented Nov 22, 2021 at 12:32

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.