Emania

Untitled

Dec 27th, 2021
1,270
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.61 KB | None | 0 0
  1.  
  2. class Writer:
  3.  
  4.     def __init__(self, path: str = 'tmp.txt'):
  5.         self.path = path
  6.  
  7.     def __enter__(self):
  8.         self.file = open(self.path, 'w')
  9.         return self
  10.  
  11.     def __exit__(self, exc_type, exc_val, exc_tb):
  12.         self.file.close()
  13.  
  14.     def print(self, text: str):
  15.         self.file.write(text + '\n')
  16.         print(text)
  17.  
  18. with Writer('file.txt') as writer:
  19.     ...
  20.     writer.print('first line')
  21.     ...
  22.     writer.print('second line')
  23.  
  24.  
  25. with open('file.txt', 'r') as f:
  26.     print('File: \n' + f.read())
  27.  
  28. '''
  29. first line
  30. second line
  31. File:
  32. first line
  33. second line
  34. '''
Advertisement
Add Comment
Please, Sign In to add comment