Skip to content

Instantly share code, notes, and snippets.

@MatheusFaria
Created February 1, 2017 16:52
Show Gist options
  • Save MatheusFaria/573ea96934df52bca0c9b5fd64039461 to your computer and use it in GitHub Desktop.
Save MatheusFaria/573ea96934df52bca0c9b5fd64039461 to your computer and use it in GitHub Desktop.
Creates an editable temp file that will be removed on close
import os
class TempFile(object):
"""Creates an editable temp file that will be removed on close"""
def __init__(self, *args, **kwds):
self.args = args
self.kwds = kwds
def __enter__(self):
self.file_obj = open(*self.args, **self.kwds)
self.name = self.kwds.get('name', None) or self.args[0]
return self.file_obj
def __exit__(self, *args):
self.file_obj.close()
os.remove(self.name)
## Usage: It must be used with a 'with' statement
if __name__ == '__main__':
with TempFile('mytemp.txt', 'w') as myfile:
myfile.write('uva')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment