6

I try to display a warning message when a file is not found in a folder but I don't understand why the warning message appears even if the layer is loaded.

I used if then else but it is not working.

from qgis.core import *
from qgis.utils import iface
import os

folder = "C:/Users/Desktop/working_folder"

os.chdir(folder)
wholelist = os.listdir(os.getcwd())

for file in wholelist:
    if "shapefile1.shp" in file:
            filefolder= folder +'\\'+file
            shapefile1 = QgsVectorLayer(filefolder,file[:-4],"ogr")
            QgsProject.instance().addMapLayer(shapefile1)
            print(filefolder)
    else:
        iface.messageBar().pushMessage("Error", "shapefile1 has not been found in :" + folder, level=Qgis.Warning)
1
  • Sorry, I've edited my code
    – Linda
    Jan 14, 2021 at 9:46

2 Answers 2

7

Your script always shows a message bar. Because you iterate on wholelist. Instead, you should iterate on file names to be checked.

First, define a list containing the file names to be checked and to be added to the project. Then check if each is in wholelist.

files_to_be_checked = ["shapefile1.shp", "shapefile2.shp"] # and so on

for file in files_to_be_checked:
    if file in wholelist:
        fileroute = folder + '\\' + file
        shapefile1 = QgsVectorLayer(fileroute, file[:-4], "ogr")
        QgsProject.instance().addMapLayer(shapefile1)
        print(fileroute)
    else:
        iface.messageBar().pushMessage("Error", file + " has not been found in " + folder, level=Qgis.Warning)
1
  • Thanks for your solution but if I do this way it loads all the layers (shapefile2, shapefile3 and so on) to my project
    – Linda
    Jan 14, 2021 at 9:58
5

You need to move the message out of the loop (or it will fire for all the missing files)

found = False
for file in wholelist:
    if "shapefile1.shp" in file:
        filefolder= folder +'\\'+file
        shapefile1 = QgsVectorLayer(filefolder,file[:-4], "ogr")
        QgsProject.instance().addMapLayer(shapefile1)
        print(filefolder)
        found = True
if !found:
    iface.messageBar().pushMessage("Error", "shapefile1 has not been found in :" + folder, level=Qgis.Warning)
1
  • Thanks Ian, I understand better how it works thanks to your answer !
    – Linda
    Jan 14, 2021 at 10:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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