1

After hours of tries and errors I can't get this right in QGIS 2.99.

I want to add a layer with the delimitedtext function in QgsVectorLayer but if I add this code to my plugin, or if I'm running it in the python-console:

import os
from qgis.core import QgsProject, QgsVectorLayer

fullname = "C:/åäö/myfile.txt"
filename = os.path.splitext(os.path.basename(fullname))[0]
uri = 'file:///%s?crs=%s&delimiter=%s&xField=%s&yField=%s&decimal=%s' % (fullname, 'EPSG:3006', ',', 'East', 'North', '.')
layer = QgsVectorLayer(uri, filename, 'delimitedtext')
if layer:
    QgsProject.instance().addMapLayer(layer)
    print("Done")
else:
    print("Error")

I'm getting an error that the file can't be opened, if I change the file path to "C:/abc/myfile.txt" everything's working fine. In QGis 2.18 i solved it with adding a .encode('utf-8') to the path, but that's not working anymore.

If I'm saving that code in a file and makeing my plugin run that file with this code, it's working. But in this way I can't use it because the file is coming from a user input through the filedialog window.

with open(u'C:/åäö/TESTdelimitedText.py') as f:
    exec(f.read())
return

or if I run it in the editor in python-console in Qgis.

In the ogr provider its working without any problems.

How do I make QgsVectorLayer delimitedtext accept a file path with special characters?

0

As you can see in issue #11274, you have to take care of non-ASCII characters yourself when using the delimited text provider. This unlike other providers that deals with it themself.

The simplest way is to import quote from urllib.parse
from urllib.parse import quote
and use it to encode your filepath
file_name = quote(path_to_file)

example:

file_names = QFileDialog.getOpenFileNames(self.iface.mainWindow(), 
                                                               "Select  files", 
                                                               "C:/", 
                                                               "Files (*.txt *.shp)")
if file_names:
    for path_to_file in file_names:
        if path_to_file.endswith('.txt'):
            layer_name = os.path.splitext(os.path.basename(path_to_file))[0]
            file_name = quote(path_to_file)
            uri = 'file:///%s?crs=%s&delimiter=%s&xField=%s&yField=%s&decimal=%s&useHeader=%s' % 
            (file_name, 'EPSG:3006', ',', 'East', 'North', '.', 'yes')
            layer = iface.addVectorLayer(uri, layer_name, 'delimitedtext')

quote() works on both QGIS 2.18 and 3.0
But remember not to use it with the 'ogr' provider if you importing shapefiles or similar.

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.