Writing to external file in game engine

I am try to write debug info to an external file in the game engine. The problem (i think) is that the commands

path = logic.expandPath("//")
file = ‘debugFile.txt’
debugFile = open(path+file, ‘w’)

Are getting executed each iteration through the code, so that the file keeps getting opened and therefore nothing gets written to the file. If i try putting it in the initialization block

if ‘init’ not in own:
own[‘init’] = 1
debugFile = open(path+file, ‘w’)

I get that “debugFile” is not defined.

Can someone tell me how to handle this, thanks

You should close the file after you are done using it.

Your missing the point, i know i have to close the file, my question is how can i open it only once.

Your missing the point, i know i have to close the file, my question is how can i open it only once.

This also does NOT work:
if ‘init’ not in own:
own[‘init’] = 1
debugFile = open(path+file, ‘w’)
else:
debugFile.write("
******** Start Game Engine ***************************

")

I get debugFile is not defined.

open(“file”, “a”)

the “a” means you want to add to the existing data. you might want to “w” when you first open so you only see the debug from the last session.

debugfile variable when get garbage collected next frame making it invalid. store the file in a game property or a module.

own["debugfile"] = open()

#OR
bge.logic.DEBUGFILE = open()

#OR
debugfile = open()

def main(cont):
    global debugfile

Thanks for your help