Intro to Python Scripting: 16 Import Points From CSV

Video Duration: 
21 minutes
Zach Downey

In this tutorial, we read through a csv text file and create new points in Rhino from these text values. The data we use for import comes from the previous export tutorial. It's important to take a close look at the data we are importing so I'll open up the CSV file in Microsoft Excel and a text editor--VIM in this case (my personal favorite text editor). In this case, we have a headerline which our script needs to handle. After we read the lines into a variable we remove the header line by using the del function. We next have to iterate through the lines using a for loop and remove the \n with the strip() method and then split the data using the split() method. The split method allows us to pass a value or character used as a split separator. In our case we will pass the comma or (',') to split the string into a list of six separate strings.

Afterword we change the strings to floats for (x,y,z) and integers for (r,g,b). This is called explicitly casting the data. To convert our strings to floats we use float(string) and to convert strings to integers we use int(string). These and more can be found in thepython docs here

Finally, we add a name to our points using the rs.ObjectName() function and then increment that name using the += shortcut. 

#Import Points from CSV
import rhinoscriptsyntax as rs
#Select a file to open
filename = rs.OpenFileName("Open CSV file","*.csv|", None, None, None)
#open the file for reading
file = open(filename, 'r')
lines = file.readlines()
#delete the first line because it's a header
del lines[0]
#print to check the data
ptNumber = 0
for line in lines:
    #remove the \n
    line = line.strip()
    #split the line by the comma
    ptInfo = line.split(',')
    x = float(ptInfo[0])
    y = float(ptInfo[1])
    z = float(ptInfo[2])
    r = int(ptInfo[3])
    g = int(ptInfo[4])
    b = int(ptInfo[5])
    pt = rs.AddPoint(x,y,z)
    color = (r,g,b)
    rs.ObjectColor(pt, color)
    name = "pt_" + str(ptNumber)
    ptNumber += 1


Please rate this tutorial below. Thanks.

Average: 5 (7 votes)

Want to Contribute?

Want to be an author? Drop us a line here we'd love to have you.

Already have a video you'd like to post? Send us a link and we'll get you going.