[GIS] pyQGIS returns invalid layer with QgsVectorLayer in QGIS 3

layerspyqgispython 3qgis-3qgsvectorlayer

I have the following problem :
I've installed all pyQGIS environment on Windows 7. I work with 64 bits version of Python 3.6 and QGIS 3.0 and PyQt5. My Windows paths are ok.

My objective is to create an empty QGS project with stand-alone python script and add layers into.

But when I try to read a shapefile (the shp is good when I open it in QGIS GUI) I get an invalid QgsVectorLayer :

import os

from qgis.core import QgsApplication, QgsProject, QgsVectorLayer
from PyQt5.QtCore import QFileInfo

QgsApplication.setPrefixPath("C:\\QGIS 3.0\\apps\\qgis", True)
qgs = QgsApplication([], False)
qgs.initQgis()

pathQGS = "C:\\path\\to\\project.qgs"
layerPath = "C:\\path\\to\\layer.shp"
fileInfo = QFileInfo(layerPath)
path = fileInfo.filePath()
baseName = fileInfo.baseName()

project = QgsProject.instance()
if os.path.isfile(pathQGS):
    os.remove(pathQGS)
project.setFileName(pathQGS)
layer = QgsVectorLayer(path, baseName, 'ogr')
if not layer.isValid():
    print("Layer is not valid")
project.addMapLayer(layer)
project.write()

qgs.exitQgis()

How can I solve this ? I checked many other topics without finding any answer to my problem.

Can you please help me ?

Best Answer

To create a QgsProject object, simply do the following:

project = QgsProject()

I tried the rest of your code and worked, it create a .qgs qgis project file, of course if your layer is not valid, it might make the .addMapLayer() call fail.

Related Question