1

I'm a beginner using Python. I had a problem loading a shapefile in QGIS 3.8 using Python, while loading a rasterfile worked perfectly.

I found the solution here: Can't load a shapefile with Python Console in QGIS?

I loaded the files like this:

path = 'D:/Users/Me/data/'
rlayer = iface.addRasterLayer(path + "/landsuit.tif", "basemap")
vlayer = iface.addVectorLayer(path + "/ne_50m_urban_areas.shp", "urban", "ogr")

Loading the vlayer like this did not work, while loading the raster layer did. When I change the vlayer path to iface.addVectorLayer(path + "\\ne_50m_urban_areas.shp", "urban", "ogr"), thus replacing "/" with "\", the code works.

Can anyone explain to me why loading the vector layer with one single forwardslash does not work, while it does work for rasterfiles? In general: When is it better to use forwardslashes and in which cases should I choose double backwardslashes? Searching the Internet I have not found any satisfying solution.

I am using Windows 10 and QGIS 3.8.

  • 2
    Use os.path.join() instead of concatenating strings. – Bjorn Nov 14 at 15:20
  • 1
    Best practice is to import os and use the os.path package for join,basename, and dirname functions. – Vince Nov 14 at 16:07