# How to store the contents of a variable in a file?

I am using the following two scripts "text" and "print":

See the Blender file at:

In the logic editor I use a Keyboard sensor connected to a "text" and "print" scripting controller. Simply pressing a specific key on the keyboard executes the script "text", but, to my surprise, I see in the console that pressing the key causing the re-execution of the script does not increment i.

System console shows:

0
0
0
0
0
0


0
1
2
3
4
5


An experienced man told me that this is normal because the reexecution of the script does not keep the variable i in memory. He told me that to remedy this, it is necessary to create an external file, use the fopen function, etc ... in order to save a variable which will be used during each re-execution of the script, but I do not know how to do it correctly.

Can you please help me to realize the script and use this external file? Can this external file simply be an internal text file in Blender's text editor? If so, what is its path to use with open ("text file path)", "r")?

• You can write standard Python in Blender scripts. Investigate variable serialisation in Python to find the standard way of saving and loading a value in a file. – rob Sep 20 '18 at 8:08
• Instead of an external file you can also use a module, like in this answer or this one, the later also shows how to get other objects in the scene, you could use an object to hold global properties. – sambler Sep 21 '18 at 8:06

I don't use BGE so I don't know how it works in BGE, but if you needed to store a value in a Python script in Blender you could store it as a custom property. The property can belong to pretty much anything, for example the current scene:

import bpy
bpy.context.scene['some_number'] = 50


When this script is run, the property gets saved with the current scene in the open .blend file. It can then be accessed by another script:

import bpy
bpy.context.scene['some_number'] += 15
print(str(bpy.context.scene['some_number']))


Everytime the script runs it adds 15 to it so the output when the script is run 5 times will be:

65
80
95
110
125


Obviously, if you open a new scene bpy.context.scene will point to a different scene so you could use a property of bpy.context.window_manager if needed.

You can use a file as well, you do not need bpy for that:

file = open("C:/SomeFile.txt", "w")
file.write("Hello World")
file.close()

file = open("C:/SomeFile.txt", "r")

It is important to make sure Blender has write permissions in the directory used for creating the file. C:/ might be protected by the OS. You can just use your project's directory.