Import CSV

Hello,

I would like to use data (text, numbers) from CSV and organize everything into a dictionary. “import csv” standard python function does not work. Is only the rs.OpenFileName() the way?

import csv
reader = csv.DictReader(open('test.csv'))

result = {}
for row in reader:
    for column, value in row.iteritems():
        result.setdefault(column, []).append(value)
print result

EDIT:
Ok, I found answer that it does not exist in IronPython; http://www.ironpython.info/index.php?title=Reading_CSV_Files, now looking for solution :slight_smile:

Hi @onrender,

If you don’t mind using RhinoScript, it has a very useful ReadDelimitedFile method.

– Dale

Thanks Dale,

Previously I started using the OpenFileName but I realized that brings up the dialog. So, kind of a combination of OpenFileName and ReadDelimitedFile but where is the path for ReadDelimitedFile?

This is how I get at csv data with python:

def read_csv(path):
    f = open(path, 'r')
    for line in f.readlines():
        values = line.strip().split(',')
        # do something with values here
        print(values)
    f.close()

As long as not huge files or anything esoteric, works well enough for me.

1 Like

I’m not sure I understand this. Did you review the sample in the help file?

– Dale

Hi Dale,

The sample includes the Rhino.OpenFileName that opens a dialog to chose the file however it has to be working without dialog and in ironpython. I am currently checking LumenWorks.Framework.IO.dll for IronPython.

Dim strFile, arrData, i, j
strFile = Rhino.OpenFileName("Open", "Comma Delimited (*.csv)|*.csv|All Files (*.*)|*.*||")
If Not IsNull(strFile) Then
  arrData = Rhino.ReadDelimitedFile(strFile)
  If IsArray(arrData) Then
    For i = 0 To UBound(arrData,1)
      For j = 0 To UBound(arrData,2)
        If IsEmpty(arrData(i,j)) Then
          Call Rhino.Print("<empty>")
        Else
          Call Rhino.Print(arrData(i,j))
        End If
      Next
    Next
  End If
End If

Just as an FYI, I believe the csv module is working in the Rhino WIP.

Hi Steve,

Yesterday, I found the following article about reading csv files in ironPython.
http://www.ironpython.info/index.php?title=Reading_CSV_Files

“import csv” works in normal Python. I am confused now.

That article was written in 2007. The Rhino WIP is using a version of IronPython that is more recent than that.

Thanks Steve, I found the answer too on;
http://developer.rhino3d.com/guides/rhinopython/python-troubleshooting-install/

@stevebaer, @Alain,

please add ReadDelimitedFile to RhinoScript for python so it can be used as well.

thanks,
c.

https://mcneel.myjetbrains.com/youtrack/issue/RH-37567

Just for the sake of compatibility.
I read some articles on the forum and I assume that there is no plan to update IronPython in V5 and it will be available only in V6. In that case I would stick to the external CSV reader as it is better to have a version for V5 as well.