# pyQGIS returns invalid layer with QgsVectorLayer in QGIS 3

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.write()

qgs.exitQgis()


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

• I just noticed you didn't describe exactly what error (messages) you are getting from running this code. Were you able to run through all lines of codes without exception? I suspect there might be some issue with the QGIS prefix path... – For Comment Jun 13 '18 at 14:59
• Exactly. I don't get any errors but when I try for example to read columns names I get : AttributeError: 'NoneType' object has no attribute 'fieldNameByIndex' – dmjf08 Jun 13 '18 at 17:43
• EDIT : when I change the value of QgsApplication.setPrefixPath it doesn't change anything in os.environ['QGIS_PREFIX_PATH'] ... Maybe this is the link to the issue. – dmjf08 Jun 13 '18 at 17:49
• I think you should have called fieldNameIndex (not fieldNameByIndex). Also you should call it via layer data provider like this: layer.dataProvider().fieldNameIndex("aFieldName") – For Comment Jun 14 '18 at 15:04
• The QgsApplication.setPrefixPath won't change the QGIS_PREFIX_PATH environ variable value. I am curious how did you install your QGIS 3 software? because that path is a little unusual. – For Comment Jun 14 '18 at 15:08

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.