TransWikia.com

Adding delimited text layer with Python outside of QGIS

Geographic Information Systems Asked by Balines on April 24, 2021

I’m trying to create a QGIS project using Jupyter environment.
Until now I managed to add a Raster layer.

I now want to add a csv file, in QGIS I would add it like that: Layer -> Add Layer -> Add delimited Text Layer.

How can I do the same using Python?

This is what I have now:

from qgis.core import QgsProject,QgsRasterLayer,QgsRaster,QgsVectorLayer
import boto3
from PyQt5.QtCore import QFileInfo
from qgis.gui import QgsMapCanvas,QtCore
from PyQt5.QtWidgets import QApplication, QWidget,QMessageBox,QDialog

project = QgsProject.instance()
#here I add the raster layer
fileInfo = QFileInfo('rasterlayer')
baseName = fileInfo.baseName()
rlayer = QgsRasterLayer('rasterlayer', basename)
if not rlayer.isValid():
   print("Layer failed to load!")
QgsProject.instance().addMapLayer(rlayer)

This is what I tried to use to add the delimited text layer and I keep geeing Invalid error.

uri='file:///coordinatestry.csv?delimiter=,&yField=y&xField=x'
layer = QgsRasterLayer(uri, 'name', 'delimitedtext')

uri = ("file:///{}?"
               "&delimiter={}"
               "&xField={}"
               "&yField={}"
               "&crs={}"
               "&decimal").format('coordinatestry.csv',
                                        ",",
                                        "x",
                                        "y",
                                        "EPSG:4326",",")
vlayer = QgsRasterLayer(uri, "layer", "delimitedtext")

fileName = 'coordinatestry.csv' # the path to the csv
fileInfo = QFileInfo(fileName)
baseName = fileInfo.baseName()
uri = "file:/"+fileName+"?delimiter=%s" % (",") # tried without the file:/ too and different delimiters  
vlayer = QgsVectorLayer(uri, baseName, "delimitedtext")

I keep getting this: <QgsRasterLayer: 'layer' (Invalid)>

The end goal is to use Atlas export as images for the coordinates in the csv on the raster layer.

Any ideas how to make the adding delimited text layer work?

Edit: Tried this as well as was suggested in comments:

uri = "file://{}/coordinatestry.csv?delimiter={}&xField={}&yField={}".format(os.getcwd(), ",", "inside_x", "inside_y")
vlayer = QgsVectorLayer(uri, "layer name you like", "delimitedtext")

Still got : <QgsVectorLayer: ‘layer name you like’ (Invalid)>

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP