Python uses 'with' to delete a file after use

I use an explicitly named file as a temporary file. To make sure that I delete the file correctly, I had to create a wrapper class for open ().

It seems to work, but

Is a] 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 cannot use tempfile.NamedTemporaryFile for many reasons

+4
source share
1 answer

I think you can make it a little easier 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 types of errors that you want to handle in different ways: Errors creating a file and errors written on it.

+7
source

Source: https://habr.com/ru/post/1340032/


All Articles