Python 使用 'with' 在使用后删除文件

标签 python

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

这似乎可行,但是

A] 安全吗?

B] 有没有更好的方法?

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

最佳答案

我猜你可以使用 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)

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

关于Python 使用 'with' 在使用后删除文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5019209/

相关文章:

python - 如何在编译时从 C 扩展模块检查 python API 的版本?

python - Heroku CLI 登录失败,错误为 "Error: ENOENT: no such file or directory, open ' H :/_netrc'"

python - 简化Python中的线程

python - 可 pickle 的动态继承?

python - 通过对象图了解 Python 日志记录

python - celery block 不执行任务

python - 如何改进 python 中的快速排序枢轴选择?

python - ipython笔记本清除所有代码

python - 如何防止打印 fixture 的值?

python - 解密 Hadoop Snappy 文件