1

Currently I am trying to import a CSV file using the python extension in QGIS and I have run into a problem that I can not seem to solve.

I am trying to do a basic import of a CSV file from a python code I created (See below) and every time the file loads the values in my attribute table become re-arranged (see image).

When I load the file from the "Create a Layer from a Delimited Text File" option it loads without a problem.

Here is a sample of my code:

uri = "file:///D:/MLB Stadiums/Test_R2/Player_Files/Espinosa_2014.csv? delimiter=%ss&xField=%s&yField=%s" % (",", "field_3", "field_4") vlayer = QgsVectorLayer(uri, "Espinosa", "delimitedtext") caps =vlayer.dataProvider().capabilities() 

Here is a comparison of what it should look like after import and what it does look like.

enter image description here

Does anyone know why it is rearranging the values?

2 Answers 2

4

It's having problems with the letter s, because your code specifies that as a delimiter (delimiter=%ss is getting interpreted as "," and "s"). Try delimiter=%s.

0
1

You can also use the format function of python if you have problems to format the string with %s. Python Format String Syntax

Your uri would look something like:

uri = "file:///D:/MLB Stadiums/Test_R2/Player_Files/Espinosa_2014.csv? delimiter={delimiter}s&xField={field3}&yField={field4}".format(delimiter=",", field3="field_3", field4="field_4") 

Or the second s in %ss after the delimiter is too much in this case. If you need it like this you can use "...delimiter=%s"%(",")+"s&xField..." for example.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.