Last active
February 7, 2019 17:03
-
-
Save xrobin/fa24fecce2dc3617151c625a70855493 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import errno | |
import tempfile | |
import os | |
class ScopedTemporaryFile(object): | |
""" Temp file to use in a with statement. | |
with ScopedTemporaryFile() as f: | |
... do stuff with f ... | |
f is a file-like object that behaves like one would expect from a | |
NamedTemporaryFile. It can be closed and opened again. | |
File is automatically deleted once the block finishes. | |
""" | |
def __init__(self, mode='w+b'): | |
self._file = tempfile.NamedTemporaryFile(mode, delete=False) | |
self._name = self._file.name | |
def __enter__(self): | |
return self | |
def __exit__(self, type, value, traceback): | |
self._file.close() | |
try: | |
os.unlink(self._name) | |
except OSError as e: | |
# file doesn't exist: already removed? | |
if e.errno != errno.ENOENT: | |
raise | |
def __getattr__(self, item): | |
return getattr(self._file, item) | |
def open(self, mode='r'): | |
""" Open the file again """ | |
self._file = open(self._name, mode) | |
def _main(): | |
with ScopedTemporaryFile() as f: | |
fname = f.name | |
print("{fn} exists? {exists}".format( | |
fn=fname, | |
exists=os.path.exists(fname) | |
)) | |
f.close() | |
print("{fn} exists? {exists} after close".format( | |
fn=fname, | |
exists=os.path.exists(fname) | |
)) | |
print("{fn} exists? {exists} after block".format( | |
fn=fname, | |
exists=os.path.exists(fname) | |
)) | |
if __name__ == "__main__": | |
_main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment