Python Scripting [1C]: Scripting to copy map aerial layers 3

So I spent a bit more time completing the script, which now looks like this:

import glob
import os
import shutil
import xml.etree.ElementTree as ET
tree = ET.parse(‘/home/patrick/Sources/CopyFiles/Source/layers.qlr’)
root = tree.getroot()
for layer in root.iter(‘layer-tree-layer’):
        sourcename = layer.get(‘name’)
        print(“Layer: ” + sourcename)
        sourcepath = “/home/patrick/Sources/CopyFiles/Source/” + sourcename + “.*”
        for file in glob.glob(sourcepath):
            destname = os.path.basename(file)
            destpath = “/home/patrick/Sources/CopyFiles/Dest/” + destname
            print(“Copying ” + file + ” to ” + destpath)

So there are a few commented out lines which we can ignore, the key parts are that it:

  • Imports the contents of a qlr file as XML and parses it
  • Gets the layer names from the XML and makes up a wildcard file spec to copy
  • Copies the files from the source to the destination.
This is saved on serverpc in the CopyFiles directory and is run in a shell window with the command

And it works exactly as expected.

This is going to be much faster than the previous script because we don’t need to start that computer up and run it in a remote window, and we also don’t need to extract layer names from the qlr file that we get from Qgis because the script can do that as well.
So it’s all go and once again I am amazed how simple and straightforward this has been. 

I have also created a second version of the script called, that is the same except it uses the shutil.move function to move the file instead of copying it. This is especially useful where you need to split up an existing directory’s contents.