# Writing contents of bpy.data.texts to folder with bpy.ops.text.save

I am reading my scripts from a folder with:

import bpy
import pathlib
for file in pathlib.Path("C:\\awesome\\scripts\\folder").iterdir():
bpy.ops.text.open(filepath = str(file))


Now i can use the scripts in blender itself and may change some stuff here and there. To save a script as a user i can use Alt + S. For scripting this procedure, blender shows a tooltip with bpy.ops.text.save() but i don't know how to define which text i want to save. I guess it will be something like:

import bpy
for text in bpy.data.texts:
bpy.data.texts.active = text
bpy.ops.text.save()


But bpy.data.texts.active is actually not available.

TL;DR: Where to define the active text?

Best, Mamu

You can find current active text object in screen.areas of text editor

area = next(area for area in context.screen.areas if area.type == 'TEXT_EDITOR')
text_obj = area.spaces.active.text


Assume that you know your text-block name, then assign that text type to active text:

area.spaces.active.text = bpy.data.texts['Text.001']


This will change the current active text object.

Without Operators

Both the reading and writing can be done without operators.

import bpy
import pathlib
for file in pathlib.Path("somefolder").iterdir():


and writing

import bpy
from pathlib import Path

for text in bpy.data.texts:
# internal
if text.is_in_memory:
continue
path = Path(bpy.path.abspath(text.filepath))
if path.exists():
path.write_text(text.as_string())