6

Currently I am writing a plugin which allows the user to quickly import a .txt file as a point layer in qgis. The .txt file is output data from a gps device and does not contain a header row. However, I was wondering if it is possible to add headers to the file while importing it as a point layer. Because the .txt structure is always the same, I always know which name a column should have.

Right now I am using addAttributeAlias but this is not satisfying as it only gives an alias to the columns.

Currently I am using the code below for importing the txt file. Is it possible somehow add a line of code in here which allows me add headers for all the columns?

txt_path = self.dlg.lineEdit_txt.text()
txt_info = "?crs=epsg:" + str(crs_rd_new) \
                   + "&type=csv&useHeader=No&xField=field_2&yField=field_3&spatialIndex=no&subsetIndex=no&watchFile=no&=&=&=&="
txt_output_filename = os.path.splitext(os.path.basename(txt_path))[0]
txt_vl = QgsVectorLayer("file:///" + txt_path + txt_info, txt_output_filename + ".txt", 'delimitedtext')
2
  • What about renaming the columns instead of adding an alias?
    – Joseph
    Commented Dec 12, 2016 at 10:56
  • The .txt files do not contain column headers. When importing them with the current script, they get assigned automatically generated headers ("field_1", "field_2", etc.) The script is used by others and they like to have descriptive headers instead of the generic ones. I sort of solved the problem by adding aliases but I would like to actually name the columns.
    – Frank
    Commented Dec 12, 2016 at 12:04

1 Answer 1

4

When it is imported as a layer in QGIS, you could use the renameAttribute() method to rename your columns.

Example:

txt_path = self.dlg.lineEdit_txt.text()
txt_info = "?crs=epsg:" + str(crs_rd_new) \
                   + "&type=csv&useHeader=No&xField=field_2&yField=field_3&spatialIndex=no&subsetIndex=no&watchFile=no&=&=&=&="
txt_output_filename = os.path.splitext(os.path.basename(txt_path))[0]
txt_vl = QgsVectorLayer("file:///" + txt_path + txt_info, txt_output_filename + ".txt", 'delimitedtext')

# To change the name of the first field
txt_vl.startEditing()
txt_vl.renameAttribute(0, 'someName')
txt_vl.updateFields()
txt_vl.commitChanges()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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