Ableton Python __init__ self file flush

119 views Asked by At

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

2

There are 2 answers

1
Neb On BEST ANSWER

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:

self.filename = "d:\members2.txt"

and when you need, you open (and then close) it.


As a suggestion, don't use f = open(...). Use the safe keyword with.

with open("d:\members2.txt", 'w') as f:
    f.write('...')

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):

with statement allows the execution of initialization and finalization code around a block of code

Moreover, you don't need to explicitly flush the file. After exiting the with block, the file is automatically closed and flushed

0
FlyingTeller On

Following the docs (on os.fsync):

If you’re starting with a Python file object f, first do f.flush(), and then do os.fsync(f.fileno()), to ensure that all internal buffers associated with f are written to disk.

So you should do

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()
        os.fsync(f.fileno())
        self.f = f