I would like to add a vector layer to QGIS using the python console (and eventually in a separate python IDE). I have run the following code from the pyqgis cookbook:
layer = QgsVectorLayer(r'//Users//rwegener//repos//correlations//co_energy_weather_shpfiles//co_energy_weather.shp',
'degree_days', "memory")
if not layer.isValid():
print('layer failed to load')
The layer loads without a problem, however the layer is not valid.
The only other pages I have found on this suggest the user to mess around with slashes so I have also tried the following ways to input the layer:
layer = QgsVectorLayer(r'/Users//rwegener//repos//correlations//co_energy_weather_shpfiles//co_energy_weather.shp',
'degree_days', "memory")
layer = QgsVectorLayer(r'/Users/rwegener/repos/correlations/co_energy_weather_shpfiles/co_energy_weather.shp',
'degree_days', "memory")
layer = QgsVectorLayer(r'\\Users\\rwegener\\repos\\correlations\\co_energy_weather_shpfiles\\co_energy_weather.shp',
'degree_days', "memory")
When I load the file into QGIS with the "add vector layer" button there are no problems.
I have tried also with the cookbook method:
layer = iface.addVectorLayer(r'//Users//rwegener//repos//correlations//co_energy_weather_shpfiles//co_energy_weather.shp',
'degree_days', "memory")
only to get the error:
AttributeError: 'NoneType' object has no attribute 'addVectorLayer'
1 Answer 1
Structure of QgsVectorLayer
is:
layer = QgsVectorLayer(data_source, layer_name, provider_name)
So, use 'ogr'
provider for shapefiles:
from qgis.core import *
# import layer
layer = QgsVectorLayer('/Users/rwegener/repos/correlations/co_energy_weather_shpfiles/co_energy_weather.shp',
'degree_days', 'ogr')
# test
if not layer.isValid():
print "Layer failed to load!"
else:
print "Layer was loaded successfully!"
-
That worked, thanks so much! To clarify, I used memory since the file is stored on my computer and didn't come from the ogr library. Why did I use that provider here?Rachel W– Rachel W2018年02月13日 19:26:08 +00:00Commented Feb 13, 2018 at 19:26
-
@RachelW you're welcome. So please, accept the answer (tick in the upper-left side)aldo_tapia– aldo_tapia2018年02月13日 19:27:08 +00:00Commented Feb 13, 2018 at 19:27
-
1@RachelW - The providers are used to read the data, 'ogr' is used most commonly for a number of file types including shapefiles. 'memory' just defines whether or your data is written to disk or if it is stored in memory.Joseph– Joseph2018年02月14日 11:32:25 +00:00Commented Feb 14, 2018 at 11:32
C://
beforeUsers//...