Warning displayed even though the file is detected in QgsMessageBar

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)

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)

Tags:

Pyqgis

Qgis 3