简体   繁体   English

仅在将第一个内容写入磁盘后才将文件写入磁盘

[英]Write a file to disk only when first content is written into it

I open a file with : 我用打开文件:

mylog = open('test.log', 'w')

and sometimes some content is written in mylog during the running time of my application ; 有时在我的应用程序运行期间一些内容会写在mylog中; but sometimes nothing is written during the running time of the app, it depends. 但有时在应用程序运行期间什么也不写,这要视情况而定。

In both cases, it seems that the file test.log is always created on disk. 在这两种情况下,似乎总是在磁盘上创建文件test.log

Is there a way of writing the file to disk only when the first content is written into it ? 只有将第一个内容写入磁盘后,才可以将文件写入磁盘吗? (with something like mylog.write('blah') for example) (例如,类似mylog.write('blah')东西)

ie if mylog.write('...') is never called, then the (empty) file test.log is not created on disk. 即,如果从未调用mylog.write('...') ,则不会在磁盘上创建(空)文件test.log

Create your own file wrapper class, storing a file object. 创建自己的文件包装器类,存储文件对象。 It needs the following methods to work with context managers and normal close function 它需要以下方法才能与上下文管理器和正常关闭功能一起使用

class MyFile():
    def __enter__(self):
        return self

    def __init__(self, path, *args):
        ''' store the path, but don't actually open the file '''
        self.path = path
        self.file_object = None
        self.args = args

    def write(self, s):
        ''' you open the file here, just before writing '''
        if not self.file_object:
            self.file_object = open(self.path, *self.args)
        self.file_object.write(self, s)

    def close(self):
        ''' close the file '''
        if self.file_object:
            self.file_object.close()

    def __exit__(self, exc_type, exc_value, exc_traceback):
        self.close()

You can either use a context manager to open/close: 您可以使用上下文管理器打开/关闭:

with MyFile('test.log', 'w') as mylog:
    mylog.write('...')

Or the classic way, calling the functions directly: 或以经典方式直接调用函数:

mylog = MyFile('test.log', 'w')
mylog.write('...')
mylog.close()

You'll have to create a wrapper object that'll only actually open the file when the first write() is called: 您必须创建一个包装对象,该对象仅在调用第一个write()时才实际打开文件:

class DelayedFile(object):
    fileobj = None

    def __init__(self, filename, *args, **kw):
        self.filename = filename
        self.args = args
        self.kw = kw

    def write(self, data):
        if self.fileobj is None:
            self.fileobj = open(self.filename, *self.args, **self.kw)
        return self.fileobj.write(data)

    def close(self):
        if self.fileobj is not None:
            return self.close() 

    def __enter__(self):
        return self

    def __exit__(self, *args, **kw):
        if self.fileobj is not None:
            return self.fileobj.__exit__(*args, **kw)

Note that this has some disadvantages; 注意,这有一些缺点。 any I/O errors on opening are not going to be raised until that first write() call. 在第一个write()调用之前,不会引发任何打开时的I / O错误。

The above proxy object implements only a subset of the standard file object API ; 上面的代理对象仅实现标准file对象API的子集; you can add more methods as needed. 您可以根据需要添加更多方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM