Saturday, 20 October 2018

pyqgis - How to create a text file containing layer names in QGIS?


My QGIS ToC contains layer groups and some layers that do not belong to any group.


I would like to create a text file containing the name of those layers that do not belong to any group.


Is there an automated way to do it?



Answer



You can do that from the QGIS Python console. Follow this workflow:





  1. Open the QGIS Python console




  2. Adjust the following line to match the path of your text file and copy the whole line to the QGIS Python console:


    textFilePath = '/tmp/non_grouped_layers.txt'

    As you can see, in the example above, I want to create a text file named 'non_grouped_layers.txt' in the folder /tmp/, I'm on a GNU/Linux machine.




  3. Press Enter.





  4. Copy the following code snippet to your QGIS Python console and, after that, press Enter a couple of times:


    # Get a reference of the layer tree
    root = QgsProject.instance().layerTreeRoot()
    tree = root.children()

    # Get names of non-grouped layers
    nonGrouped = []
    for node in tree:

    if isinstance( node, QgsLayerTreeLayer ):
    nonGrouped.append( node.layerName() )

    #Save the nonGrouped list as text file
    f = open( textFilePath, 'wt')
    f.write( '\n'.join( nonGrouped ) )
    f.close()


You should now have your text file with the list of non-grouped layers.





In the screenshot you can see my QGIS ToC arrangement and the text file I get from running the code snippet.


enter image description here


If you face troubles, tell me.


No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...