I am trying to load a csv file in processing.py as a table. The Java environment allows me to use the loadTable() function, however, I'm unable to find an equivalent function in the python environment.
Asked
Active
Viewed 594 times
0
-
1Does using the standard python library to read CSV's not work for your use-case? https://docs.python.org/2/library/csv.html – justderb Apr 18 '17 at 06:17
-
[try this](http://stackoverflow.com/questions/3518778/how-to-read-csv-into-record-array-in-numpy) – R.A.Munna Apr 18 '17 at 06:19
-
1Processing.py looks to have `loadTable` now: https://github.com/jdf/processing.py/blob/7c30e038600c221c5b70590a50160d918b5dd86b/mode/examples/Topics/AdvancedData/LoadSaveTable/LoadSaveTable.pyde#L44 – justderb Apr 18 '17 at 06:21
2 Answers
0
The missing functionality could be added as follows:
import csv
class Row(object):
def __init__(self, dict_row):
self.dict_row = dict_row
def getFloat(self, key):
return float(self.dict_row[key])
def getString(self, key):
return self.dict_row[key]
class loadTable(object):
def __init__(self, csv_filename, header):
with open(csv_filename, "rb") as f_input:
csv_input = csv.DictReader(f_input)
self.data = [Row(row) for row in csv_input]
def rows(self):
return self.data
This reads the csv file into memory using Python's csv.DictReader
class. This treats each row in the csv file as a dictionary. For each row, it creates an instance of a Row
class which then lets you retrieve entries in the format required. Currently I have just coded for getFloat()
and getString()
(which is the default format for all csv values).

Martin Evans
- 45,791
- 17
- 81
- 97
0
You could create an empty Table
object with this:
from processing.data import Table
t = Table()
And then populate it as discussed at https://discourse.processing.org/t/creating-an-empty-table-object-in-python-mode-and-some-other-hidden-data-classes/25121
But I think a Python Dict as proposed by @martin-evans would be nice. You load it like this:
import csv
from codecs import open # optional to have the 'enconding="utf-8"' in Python 2
with open("data/pokemon.csv", encoding="utf-8") as f:
data = list(csv.DictReader(f)) # a list of dicts, col-headers as keys

villares
- 333
- 2
- 12