I'm writing an ableton python script. This one writes the string to the file:
class LaunchControl(ControlSurface):
def __init__(self, c_instance):
super(LaunchControl, self).__init__(c_instance)
f = open("d:\members2.txt", "w")
f.write('START ok\n\n')
f.flush()
But this one does not and I don't see any error in the log. The only difference is the last line:
class LaunchControl(ControlSurface):
def __init__(self, c_instance):
super(LaunchControl, self).__init__(c_instance)
f = open("d:\members2.txt", "w")
f.write('START ok\n\n')
f.flush()
self.f = f
I want to use f in other functions of LaunchControl class
Leaving your file opened is a bad habit. What happens if other applications need to read or write to the same file? Since you've opened it in write mode, it is blocked and no other application can access it until it is closed (released).
If you want to access your file from multiple functions or scripts, save it's filename:
and when you need, you open (and then close) it.
As a suggestion, don't use
f = open(...)
. Use the safe keywordwith
.After exiting from the with scope, the resource (in this case a file stream) is automatically closed and released. It is safety closed even in the case of exceptions thrown. The python documentation says (emphasis added):
Moreover, you don't need to explicitly flush the file. After exiting the with block, the file is automatically closed and flushed