3

I want to load CSV file to QGIS. It works if I use the strings below:

uri ="file:///C:/Users/User/Desktop/Alex working/Tracks//Track.csv?delimiter={}&crs=epsg:25831&xField={}&yField={}".format(",", "Easting", "Northing")
vlayer = QgsVectorLayer(uri, "layer name you like", "delimitedtext")
if not vlayer.isValid():
    print("Layer failed to load!")

But if I pass Filepath and name of the file to variable, the file fails to load.

import os
from qgis.core import (QgsVectorLayer)
Path="C:/Users/User/Desktop/Alex working/Tracks"
name="Track.csv"
uri ="file:///Path/name?delimiter={}&crs=epsg:25831&xField={}&yField={}".format(",", "Easting", "Northing")
vlayer = QgsVectorLayer(uri, "layer name you like", "delimitedtext")
if not vlayer.isValid():
    print("Layer failed to load!") 

What am I missing?

6

in your uri variable, Path/name is a literal string, not the variables Path and name.

Try:

uri ="file:///{}/{}?delimiter=,&crs=epsg:25831&xField=Easting&yField=Northing".format(Path, name)

Or using "f'' strings"

uri =f"file:///{Path}/{name}?delimiter=,&crs=epsg:25831&xField=Easting&yField=Northing"
0
5

You can also use this structure:

uri ="file:///" + Path + "/" + name + "?delimiter=,&crs=epsg:25831&xField=Easting&yField=Northing"
0

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.