Python使用'with'删除我们后面的文件

2024-09-24 16:35:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用一个显式命名的文件作为临时文件。为了确保正确删除文件,我不得不为open()创建一个包装类。在

这似乎有用,但是

A]安全吗?在

有更好的办法吗?在

import os

string1 = """1. text line
2. text line
3. text line
4. text line
5. text line
"""
class tempOpen():
    def __init__(self, _stringArg1, _stringArg2):
        self.arg1=_stringArg1
        self.arg2=_stringArg2

    def __enter__(self):
        self.f= open(self.arg1, self.arg2)
        return self.f

    def __exit__(self, exc_type=None, exc_val=None, exc_tb=None):
        self.f.close()
        os.remove(self.arg1)

if __name__ == '__main__':

    with tempOpen('tempfile.txt', 'w+') as fileHandel:
        fileHandel.write(string1)
        fileHandel.seek(0)
        c = fileHandel.readlines()
        print c

供参考:我不能用tempfile.NamedTemporaryFile有很多原因


Tags: 文件textselfnoneosdeflineopen
1条回答
网友
1楼 · 发布于 2024-09-24 16:35:32

我想您可以用contextlib.contextmanager来简化一下:

from contextlib import contextmanager

@contextmanager
def tempOpen( path, mode ):
    # if this fails there is nothing left to do anyways
    file = open(path, mode)

    try:
        yield file
    finally:
        file.close()
        os.remove(path)

有两种不同的错误需要处理:创建文件的错误和写入文件的错误。在

相关问题 更多 >