0

我正在编写一个ableton python 脚本。这个将字符串写入文件:

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

但是这个没有,我在日志中看不到任何错误。唯一的区别是最后一行:

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

我想在 LaunchControl 类的其他功能中使用 f

4

2 回答 2

1

让你的文件保持打开状态是一个坏习惯。如果其他应用程序需要读取或写入同一个文件会怎样?由于您已以写入模式打开它,因此它被阻止并且在关闭(释放)之前没有其他应用程序可以访问它。

如果您想从多个函数或脚本访问您的文件,请保存它的文件名:

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

当你需要时,你打开(然后关闭)它。


作为建议,不要使用f = open(...). 使用安全关键字with

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

退出 with 范围后,资源(在本例中为文件流)会自动关闭和释放。即使在抛出异常的情况下,它也是安全关闭的。python文档说(强调):

with语句允许围绕代码块执行初始化和终结代码

此外,您不需要显式刷新文件。退出with块后,文件自动关闭并刷新

于 2018-09-29T08:30:51.223 回答
-1

按照文档(上os.fsync):

如果您从 Python 文件 object 开始f,首先 do f.flush(),然后 do os.fsync(f.fileno()),以确保与 f 关联的所有内部缓冲区都写入磁盘。

所以你应该做

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
于 2018-09-29T08:34:30.890 回答