5

I am trying to import several CSV-files using Python. However, my code does not work. Furthermore, the coordinates are in DMS-format and I am unsure on how to implement that to my code.

import os.path, glob
layers=[]
for file in glob.glob('/Users/NAME/Desktop/gis/weights/*'):
    uri="file:///"+file+"?type=csv&xField=LON&yField=LAT&spatialIndex=no&subsetIndex=no&watchFile=no&crs=epsg:4326"
    vlayer = QgsVectorLayer(uri, os.path.basename(file), "delimitedtext")
    vlayer.addAttributeAlias(0,'x')
    vlayer.addAttributeAlias(1,'y')
    layers.append(vlayer)
QgsMapLayerRegistry.instance().addMapLayers(layers)

When running my code I get the following error-messages:

Traceback (most recent call last): 
File "/Applications/QGIS3.10.app/Contents/Frameworks/Python.framework/Versions/Current/lib/python3.7/code.py", line 90, in runcode exec(code, self.locals) File "<input>", line 1, in <module> 
File "<string>", line 10, in <module> NameError: name 'QgsMapLayerRegistry' is not defined

Sample of CSV-file

Below is a sample of the data in the CSV-file.

5
  • Yes, that is the code that I am trying to use.
    – timpan
    Commented Sep 3, 2020 at 12:12
  • ``` Traceback (most recent call last): File "/Applications/QGIS3.10.app/Contents/Frameworks/Python.framework/Versions/Current/lib/python3.7/code.py", line 90, in runcode exec(code, self.locals) File "<input>", line 1, in <module> File "<string>", line 10, in <module> NameError: name 'QgsMapLayerRegistry' is not defined ```
    – timpan
    Commented Sep 3, 2020 at 12:20
  • @BERA I have added a sample of the data that I am trying to import.
    – timpan
    Commented Sep 3, 2020 at 12:24
  • @user2856 Clarified!
    – timpan
    Commented Sep 3, 2020 at 12:30
  • 1
    gis.stackexchange.com/q/244452/2856
    – user2856
    Commented Sep 3, 2020 at 12:32

2 Answers 2

6

For QGIS 3, QgsMapLayerRegistry's functionality has been moved to QgsProject. That's why you get that error.

So, to add a layer, you should use that structure:

QgsProject.instance().addMapLayers(layers)
1
  • Thank you Kadir! That was indeed the major problem with the code. Also, I found that importing one CVS-file gives you the code that is supposed to follow after the filename (in order to fetch the coordinates, state DMS etc).
    – timpan
    Commented Sep 3, 2020 at 13:31
3

I use this Python function to parse vector files with random text formatted point features:

Txt file example:

y   x
58 57 39.71;73 57 32.26

Python function:

def load_layer_from_text(text_file_path, x_field_name, y_field_name, delimeter, decimal_separator, epsg_number, DMS=False):
    '''Add layer from text file'''
    uri = qgis.core.QgsDataSourceUri()
    layer_name = 'temp_layer'

    text_file_path_encoded = urllib.parse.quote(text_file_path)

    uri_as_string = \
        f'file:///{text_file_path_encoded}?' \
        f'delimiter={delimeter}' \
        f'&xField={x_field_name}' \
        f'&yField={y_field_name}' \
        f'&crs=epsg:{str(epsg_number)}' \
        f'&detectTypes=yes' \
        f'&decimalPoint={decimal_separator}'
    if DMS:
        uri_as_string += '&xyDms=yes'


    layer = qgis.core.QgsVectorLayer(uri_as_string, layer_name, 'delimitedtext')
    if layer.isValid():
        return layer
    else:
        print('Error! Vector layer was not validated:')
        print(uri_as_string)

        return None

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