I'm working on a project using the QGIS Python API. I seem to be having some issues with opening a vector layer from a shapefile in my standalone application. This is the Python script I'm using to test opening the layer:

#   Import statements
from qgis.core import *
import os

#   Instantiate the QGIS Application
GUIEnabled = True
app = QgsApplication([], GUIEnabled)
#   Update prefix path
app.setPrefixPath("C:\OSGeo4W64\apps\qgis", True)

#   File to be read by the application
vector_source = "absolute_path_to_file"

#   Read layer from file
layer = QgsVectorLayer(vector_source, "Vector_Layer", "ogr")

#   DEBUG: Test if the file path points to a valid file
print "File Path points to a file: ", os.path.isfile(vector_source)

#   DEBUG: Test if the layer initialized correctly
print "Output of layer.isValid(): ", layer.isValid()

layer.isValid() returns false when I run the script. I checked to make sure the file was valid by opening it in the QGIS GUI, which worked. I also checked out the answer to Creating QGIS layers in python console vs stand-alone application, but the answer there is specific to Mac users, and I am running on Windows 8.

1 Answer 1


You need to escape your backslashes when you defined your paths for the QGIS application (I tend to use forward slashes).

So you should replace:

app.setPrefixPath("C:\OSGeo4W64\apps\qgis", True)


app.setPrefixPath("C:/OSGeo4W64/apps/qgis", True)


app.setPrefixPath(r"C:\OSGeo4W64\apps\qgis", True)


  • 1
    Thank you. This resolved the issue I was facing. It's strange that this wasn't a problem in the Python console in QGIS.
    – Benjamin
    Dec 5, 2016 at 11:43
  • @Benjamin - Most welcome, glad it helped! You mean using single backslashes isn't a problem in the console?
    – Joseph
    Dec 5, 2016 at 11:46
  • It wasn't when I tested the code in the console that's in the QGIS GUI
    – Benjamin
    Dec 5, 2016 at 11:48
  • @Benjamin - Yeah I think QGIS is quite forgiving when it comes to little things like this and solves it automatically. Or atleast that's what I experienced several times =)
    – Joseph
    Dec 5, 2016 at 11:51

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.