# How to add text in blender using python

I am trying to add a series to text in blender using python Presently I am using these lines of code

bpy.ops.object.text_add()
ob=bpy.context.object
ob.data.body = "my text"


Is there a way that I can add my text while adding the text object itself?

• This question needs a bit more clarity – are you simply trying to reduce the number of lines of code, improve the efficiency of the code, or something else? – Christopher Gearhart Jan 12 '20 at 0:54
• reduce the lines of code! – Raghunandan Venkatesh Jan 12 '20 at 13:16

The preferred way to perform the above operation would be to create the data blocks and link them to the scene using the "low-level" API - RNA methods and attributes - instead of operators to achieve better runtimes and avoid incorrect context issues.

The following code replaces the operator call above to achieve the same behavior:

font_curve = bpy.data.curves.new(type="FONT",name="Font Curve")
font_curve.body = "my text"
font_obj = bpy.data.objects.new("Font Object", font_curve)

bpy.data.curves.new(type="FONT",name="Font Curve").body = "my text"

• making above a method eg def add_text(body_text, collection=bpy.context.collection): will also ultimately reduce the lines of code if adding a lot of text objects. – batFINGER Jan 13 '20 at 18:36