简体   繁体   中英

Python QGIS: Layer failed to load

I am trying to load a QGIS vector layer from a SHP file in Python. Whenever I run it, layer.isValid() always returns False (or "Layer is not valid!" in this case). I'm not sure what I am doing wrong here, or if I have instantiated the QgsVectorLayer variable incorrectly.

import sys
import os
from qgis.core import *
import matplotlib.pyplot as plt
from matplotlib.path import Path
import matplotlib.patches as patches


QgsApplication.setPrefixPath("/usr", True)
qgs = QgsApplication(sys.argv, False)
qgs.initQgis()

layer=QgsVectorLayer("/Users/ANON/Desktop/MassShapeFiles/MassachusettsTownBoundaries.shp", "MassachusettsTownBoundaries", "ogr")
providers = QgsProviderRegistry.instance().providerList()
for provider in providers:
    print provider
if not layer.isValid():
    print "Layer failed to load!"
provider = layer.dataProvider()

Thank you!

I think your path is malformed. Looking to path structure I assume you are in a windows system, so your windows path should be:

"\\Users\\ANON\\Desktop\\MassShapeFiles\\MassachusettsTownBoundaries.shp"

with double backslash notation to avoid python misunderstandings

you are in windows system. but you have used qgis prefix path as linux system. Get the proper qgis prefix path from qgis python console by printing QgsApplication.showSettings.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM