1
|
import os
|
2
|
|
3
|
|
4
|
# allows the caller, when using "with" keyword, access a temporary file with the desired content that is deleted
|
5
|
# when "with" context is destroyed
|
6
|
class TemporaryFile(object):
|
7
|
def __init__(self, file_name, content):
|
8
|
self.file_name = file_name
|
9
|
self.content = content
|
10
|
|
11
|
def __enter__(self):
|
12
|
# if content was passed, write it to a new file specified by the given file name
|
13
|
if len(self.content) > 0:
|
14
|
with open(self.file_name, "wb" if isinstance(self.content, bytes) else "w") as file:
|
15
|
file.write(self.content)
|
16
|
return self.file_name
|
17
|
|
18
|
def __exit__(self, type_, value, traceback):
|
19
|
if len(self.content) > 0:
|
20
|
# if content was passed then the file has been created => delete it.
|
21
|
os.remove(self.file_name)
|