[GIS] PyQGIS import csv- QGIS 3.4

pyqgispythonqgis-3

This is seemingly pretty simple. I have a csv file I want to add to the map. It is comma delimited and there is no lat/lon information. I will join it to a shapefile later. I used other examples from stackoverflow and this documentation in the QGIS cookbook to do it. I can add it with the following code:

uri = 'file:///Users/ep9k/Desktop/SandraMonson/CountByZip.csv?delimiter=,'
csv_file = QgsVectorLayer(uri, 'Patient Data', 'delimitedtext')
QgsProject.instance().addMapLayer(csv_file)

This adds the file to the map. But in the attribute table it reads all data as column headers. The attribute table looks like this:
enter image description here

ZipCode, PatientCount, StateOrProvince should be the column headers, with data below. How can I read the first line as column headers and the rest as data in those columns?

Another thought I have, after looking at the QGIS cookbook documentation, I went into PyQGIS API documentation and into Module>Core Library> and looked for QgsVectorLayer and QgsProject, and it seems counterintuitive as a csv file is not a vector layer.

Best Answer

I was able to answer my own question using this helpful thread about a related question: Trouble loading non-spatial data via CSV using Python for standalone script

It looks like my csv file was formatted incorrectly. The file was originally an excel file (.xls) and I saved it as a CSV file with utf-8 formatting. QGIS didn't like something about that so I re-saved my file as a plain ".csv" with no formatting.

However, I had not found an example for QGIS 3.x of importing a non-spatial (without lat/lon coordinates) .csv so maybe this can serve as an example of how to do that.