How to store the contents of a variable in a file?
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")
text = file.read()
print(text)
file.close()


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.

I don't think it is possible to write to Blender's text block this way. I might be wrong here. It does not seem to me like a very elegant way to store a variable anyway. I would use custom properties.