Python Text to 3dObject
To get the selection, remember the lines are displayed from 1, but counted from 0 in the text buffer.

&gt;&gt;&gt; t = D.texts['Text.002']
&gt;&gt;&gt; t.current_character
10

&gt;&gt;&gt; t.current_line_index
12

&gt;&gt;&gt; t.select_end_character
4

&gt;&gt;&gt; t.select_end_line_index
16


To set the selection

&gt;&gt;&gt; t.select_set(
select_set()
Text.select_set(line_start, char_start, line_end, char_end)
Set selection range by line and character index

&gt;&gt;&gt; t.select_set(0, 0, 4, 22)




Text file buffer.

&gt;&gt;&gt; for i, l in enumerate(t.lines):
...     i, l.body
...     
(0, 'import bpy')
(1, 'import bmesh')
(2, 'context = bpy.context')
(3, '')
(4, 'context.tool_settings.mesh_select_mode = (False, False, True) # faces')
(5, 'ob = context.edit_object')
(6, 'me = ob.data')