Another documentation gap that drives me mad is that the Python equivalent of an example like the (Java) Table t = new Table()
is missing.
Table is missing from the Py.Processing.org/reference and nobody tells you how to import the needed constructor with from processing.data import Table
So here you go:
from processing.data import Table
def setup():
table = Table()
table.addColumn("id")
table.addColumn("species")
table.addColumn("name")
newRow = table.addRow()
newRow.setInt("id", table.getRowCount() - 1)
newRow.setString("species", "Panthera leo")
newRow.setString("name", "Lion")
saveTable(table, "data/new.csv")
For the curious, there are some other Python<->Java compatibility-helping objects hidden on this data
module.
import processing
print(dir(processing.data))
['DoubleDict', 'DoubleList', 'FloatDict', 'FloatList', 'IntDict', 'IntList', 'JSONArray', 'JSONObject', 'JSONTokener', 'LongDict', 'LongList', 'Sort', 'StringDict', 'StringList', 'Table', 'TableRow', 'XML', '__name__']
Why not use the nice built-in Python csv
module you might ask?
import csv
with open('names.csv', 'w') as csvfile: # Python 2 has no encoding on open()
fieldnames = ["species", "name"]
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
writer.writeheader()
writer.writerow({"species" : "Panthera Leo", "name" : u"Léo the Lion"})
I had problems with unicode strings, (non-ASCII characters) encoding it writes the file as ISO-885914 and not UTF-8 I would prefer.