Created
November 17, 2018 09:58
Revisions
-
heykarimoff created this gist
Nov 17, 2018 .There are no files selected for viewing
This file contains hidden or 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 charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,34 @@ import json from contextlib import contextmanager data = {'key': 1234} with open('the_json_file.json', 'wt') as json_file: json.dump(data, json_file) with OpenFile('the_json_file.json', 'wt') as json_file: json.dump(data, json_file) with open_file('the_json_file.json', 'wt') as json_file: json.dump(data, json_file) # Version 1 class OpenFile: def __init__(self, filename, mode): self.filename = filename self.mode = mode def __enter__(self): self.file = open(self.filename, self.mode) return self.file def __exit__(self): self.file.close() # Version 2 @contextmanager def open_file(filename, mode): file = open(filename, mode) yield file file.close()