3

I'm using the following QGIS 2.8 Python code to save results to a txt file

QgsVectorFileWriter.writeAsVectorFormat(inputLayer, "D:/dstest/my_csv", "CP1250", None, "CSV",True)

I would like to be able to write the results to a TAB delimited txt file as opposed to the comma delimited one produced by the statement above. Can this be done through QgsVectorFileWriter.writeAsVectorFormat or is there another way?

  • Do you want to write the attributes of the shape file to a text file? or am I wrong? – User123 May 22 '15 at 12:25
  • Yes, thanks. I'd like to write the attributes of the selected polygons (code prior to the above line does the selecting and the above line writes just the attributes of the selected polygons) to a tab delimited text file. – ian May 22 '15 at 12:43
2

The following code produces a tab delimited txt file:

#Create python list
createopts=["SEPARATOR=TAB"]
#Use list in QgsVectorFileWriter
QgsVectorFileWriter.writeAsVectorFormat(inputLayer, "D:/dstest/my_csv", "CP1250", None, "CSV", True, "", "", createopts)

Thanks to @underdark for helping with this.

Ian

  • This is usefull – Marcel GJS Jun 9 '17 at 8:24
2

The layer creation option separator should be helpful, i.e. SEPARATOR=TAB

Based on the QgsVectorFileWriter.writeAsVectorFormat docs, this should do it (untested):

QgsVectorFileWriter.writeAsVectorFormat(inputLayer, "D:/dstest/my_csv", "CP1250", 
                                        None, "CSV", True, "", "", ["SEPARATOR=TAB"])
  • Thanks underdark, I'd had a look at the documentation but couldn't manage to get anything to work. Replacing my code with yours results in the following error: argument 7 has unexpected type 'int' – ian May 26 '15 at 10:56
  • @ian Try now. argument 7 has to be a string. – underdark May 26 '15 at 17:25
  • Thanks underdark, the code now executes without error however it is still producing a file with commas as separators. It seems as though argument 8 is being ignored. I switched argument 7 and 8 round and it still just produces a csv – ian Jun 1 '15 at 9:30
  • Try argument 9, I might have miscounted the number of arguments in the docs. – underdark Jun 1 '15 at 11:16
  • Thanks underdark, you were right it should be the 9th argument. However the code as its stands still didn't work. I went back to the documentation and worked out why - the creation options need to be passed as a list, not a string. I've added the code to a new answer for future reference – ian Jun 2 '15 at 10:28

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.