I am using an explicitly named file as a temporary file. In order to make sure I delete the file correctly I've had to create a wrapper class for open().
This seems to work but
A] is it safe?
B] is there a better way?
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
FYI: I cant use tempfile.NamedTemporaryFile for a lot of reasons
I guess you can do a bit simpler with 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)
There are two kinds of errors you want to handle differently: Errors creating the file and errors writing to it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With