1

I'm trying to load a shapefile into QGIS using iface.addVectorLayer, but whenever I do this, I get an error message "Layer is not valid: etc ..."

However, if I try to load the same shapefile use the menu dialog "Add Vector Layer", it loads fine. I have loaded raster files, so I know it's not some funny with the path name.

I'm sure I'm missing something obvious here, but what?

enter image description here

This line works:-

layer1 = iface.addRasterLayer("H:\Mapping Stuff\NE1_50M_SR_W\NE1_50M_SR_W\NE1_50M_SR_W.tif", "basemap")

This doesn't:-

layer2 = iface.addVectorLayer("H:\Mapping Stuff\ne_50m_urban_areas\ne_50m_urban_areas.shp", "urban", "ogr")
  • Please post your code. – underdark Jun 1 '15 at 17:42
  • Can you post your code (only the piece that loads the shp) – luca76 Jun 2 '15 at 6:49
  • Are you 100% sure your vector file path is right? I just test it with no problems on my machine. – Germán Carrillo Jun 2 '15 at 14:42
  • 1
    @gcarrillo - I also received the same error message as the OP if only single slashes are used for shapefiles instead of double. Perhaps a platform issue as I use Windows? – Joseph Jun 2 '15 at 15:02
  • @gcarrillo - Yes, it's correct; here is the path copied using "Copy as Path" :-"H:\Mapping Stuff\ne_50m_urban_areas\ne_50m_urban_areas.shp" – LeighM Jun 2 '15 at 15:05
1

QGis likes path to be using forward slash, like on Unix system. So, if you change all of the backslashes to forward slash then it will work on your windows box.

0

Try this (note the double slashes for the directory in which your shapefile resides in):

layer2 = iface.addVectorLayer("H:\Mapping Stuff\ne_50m_urban_areas\\ne_50m_urban_areas.shp", "urban", "ogr")
  • Not completely sure why a single slash works for rasters and not for vectors, perhaps someone can enlighten us with this =) – Joseph Jun 2 '15 at 14:22
  • 1
    Joseph's solution of placing double slashes in front of filename (\\ne_50m_urban_areas.shp) works for me. After many attempts, none of the previous suggestions did. – J. Browne Dec 15 '16 at 3:17
0

In C and C++, and as far as I know also Python, backslashes are used to identify special characters. For instance,

'\t' = TAB character

'\n'= New Line

Pay attention: lowercase; this might explain why one of your strings does not work. In order to inform the compiler (interpreter) that we want an actual backslash inside of a string, we must type two backslashes:

'\\'

Windows accepts both separators, \ and /, so in principle it should be ok to use "h:/blabla".

By the way, this is an old trick that ages back to Pascal; in that language, quotes can be inserted in a string by duplication, eg. "Here are some ""quotes"" !".

In C/C++ (?Python?), the equivalent is "Here are some \"quotes\" !"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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