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?

2
  • Do you want to write the attributes of the shape file to a text file? or am I wrong?
    – User123
    Commented May 22, 2015 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
    Commented May 22, 2015 at 12:43

2 Answers 2

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

1
  • This is usefull
    – Marcel GJS
    Commented Jun 9, 2017 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"])
6
  • 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
    Commented May 26, 2015 at 10:56
  • @ian Try now. argument 7 has to be a string.
    – underdark
    Commented May 26, 2015 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
    Commented Jun 1, 2015 at 9:30
  • Try argument 9, I might have miscounted the number of arguments in the docs.
    – underdark
    Commented Jun 1, 2015 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
    Commented Jun 2, 2015 at 10:28

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.