1

I've been trying to load a .shp file using PyQGIS, but layer.isValid() is always false. I've tried looking around at past solutions for the problem and nothing is working for me. This is my code currently:

from qgis.core import *
from PyQt4.QtGui import QApplication

app = QApplication([])
QgsApplication.setPrefixPath('C:\\OSGeo4W\\apps\\qgis\\', True)
QgsApplication.initQgis()

layer = QgsVectorLayer('C:\\path\\to\\file.shp', 'name', 'ogr')
print layer.isValid()

I've also tried using forward slashes instead of double backslashes in my paths, which doesn't work either. I'm on Windows 10, running Python 2.7.5 with OSGeo4W.

3
  • Can you load the layer in QGIS or any other GIS programs?
    – Liam G
    Commented Nov 28, 2017 at 5:12
  • Yes, I'm using in a QGIS project just fine. Commented Nov 28, 2017 at 5:17
  • You probably need to set your paths correctly. You could run this batch file described in this post before running your script.
    – Joseph
    Commented Nov 28, 2017 at 10:39

1 Answer 1

1

Try using the app reference:

app = QApplication([])
app.setPrefixPath('C:\\OSGeo4W\\apps\\qgis\\', True)
app.initQgis()

Your Answer

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

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