2

I'm want to run the processing tool 'merge vector layers' (native:mergevectorlayers) using PyQGIS. The input layers are XLS files with the prefix "WeeklyContacts". A new XLS file is added to the directory each week and I want to run the algorithm every week to perform further spatial analyses.

I'd rather not have to manually select the files to being the script each week.

QGIS v 3.4

How do I input layers with the same prefix and file type rather than using code such as below?

params = {'LAYERS':['//gfwavsql/xxxx/WeeklyContacts-2018-10-12.xls','//gfwavsql/xxxx/WeeklyContacts-2018-10-16.xls','//gfwavsql/xxxx/WeeklyContacts-2018-10-23.xls','//gfwavsql/xxxx/WeeklyContacts-2018-10-30.xls','//gfwavsql/xxxx/WeeklyContacts-2018-11-06.xls'],'CRS':None,'OUTPUT':'memory:'}
processing.run("native:mergevectorlayers", params)

enter image description here

  • 1
    Use glob module glob.glob('WeeklyContacts*.xls') – Fran Raga Jul 23 at 9:59
  • @FranRaga so something like...params = {'LAYERS':[glob.glob('WeeklyContacts*.xls'),'//gfwavsql/xxxx/'],'CRS':None,.... Sorry I don't know how to combine that line of code. There is no reference to glob in QGIS 3.4 cookbook – James B Jul 23 at 10:06
  • 1
    glob is a python module, it has nothing to do with QGIS. This line return a list for example glob.glob(r'D:\test\WeeklyContacts*.xls') and you only need pass this list in LAYERS input. If you want add more path in this list, make list.append(...) – Fran Raga Jul 23 at 10:15
  • @FranRaga I'm sorry, would you be able to provide a complete answer with all lines of code? Again, I don't know if I need to use import os, glob at the start etc etc... – James B Jul 23 at 10:24
  • 1
    As @FranRaga mentioned, you could use it like: params = {'LAYERS':glob.glob(r'D:\test\WeeklyContacts*.xls'),'CRS':None,'OUTPUT':'memory:'}. You may need to include import glob beforehand. – Joseph Jul 25 at 14:35
4
+50

You only need this:

# import glob library
import glob 

# Create a list, glob return a list with file paths
layers = glob.glob('D:\test\WeeklyContacts*.xls')

# Put glob list result in 'LAYERS' processing input
params = {'LAYERS': layers ,'CRS':None,'OUTPUT':'memory:'}
result = processing.run("native:mergevectorlayers", params)

# If you want add result to canvas
QgsProject.instance().addMapLayer(result['OUTPUT'])

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.