Created
February 1, 2017 16:52
-
-
Save MatheusFaria/573ea96934df52bca0c9b5fd64039461 to your computer and use it in GitHub Desktop.
Creates an editable temp file that will be removed on close
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 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