# Creating curves in Python

I am new to Blender scripting and I am getting some unexpected behavior when trying to add a curve through a Python script. I am using this code:

import bpy
import math
import pdb
from mathutils import Vector

# print all objects
for obj in bpy.data.objects:
print(obj.name)
if("Curve" in obj.name):
print("found")
bpy.data.objects.remove(obj)

for cur in bpy.data.curves:
print(cur.name)
bpy.data.curves.remove(cur)

# sample data
coords = [(1,0,1), (2,0,0), (3,0,1)]

# create the Curve Datablock
curveData = bpy.data.curves.new('myCurve', type='CURVE')
curveData.dimensions = '3D'
curveData.resolution_u = 2

# map coords to spline
polyline = curveData.splines.new('POLY')
for i, coord in enumerate(coords):
x,y,z = coord
polyline.points[i].co = (x, y, z, 1)

# create Object
curveOB = bpy.data.objects.new('myCurve', curveData)
curveData.bevel_depth = 0.01

# attach to scene and validate context
scn = bpy.context.scene
scn.objects.active = curveOB


And this is the result I get.

I am confused why there are four coordinates. Blender seems to create one additional point at the coordinate origin (0,0,0), connecting it with the last point from my data. Why is this happening and how can I avoid it?

• To run the script above in Blender 2.8, I think the last two lines need to be changed to scn.collection.objects.link(curveOB) (see this link) and bpy.context.view_layer.objects.active = curveOB (see this link) – Trevor Jan 19 at 5:35

The solution was simple enough. I changed

polyline.points.add(len(coords))


to

polyline.points.add(len(coords)-1)


as found here:

http://blenderscripting.blogspot.de/2011/05/blender-25-python-bezier-from-list-of.html

• Can you elaborate, eg splines.new(...) returns a spline with one point. – batFINGER Aug 19 '16 at 9:48
• That's strange, because output of for i in range(len(polyline.points)): print(polyline.points[i].co.xy) does not contain (0,0) – Oleg Skripnyak Jul 27 '18 at 12:37
• However this code polyline = curveData.splines.new('POLY') for i in range(len(polyline.points)): print(polyline.points[i].co.xy) prints only one point (0,0) ! So by creation, there is always one point in the array, and you even can access it polyline.points[0].co = (1, 1, 1, 1) but nothing changes. That's strange behavior, seem a bug – Oleg Skripnyak Jul 27 '18 at 13:45