mytempfile.py 565 B

123456789101112131415161718
  1. import tempfile
  2. import os
  3. import shutil
  4. class MyTempFile:
  5. def __init__(self, file_path):
  6. self.file_path = file_path
  7. def __enter__(self):
  8. self.tmp_file = tempfile.NamedTemporaryFile('w', dir='.', delete=False)
  9. self.tmp_file_path = os.path.relpath(self.tmp_file.name, '.')
  10. shutil.copyfile(self.file_path, self.tmp_file_path)
  11. return self
  12. def __exit__(self, exc_type, exc_value, exc_traceback):
  13. self.tmp_file.close()
  14. if os.path.isfile(self.tmp_file_path):
  15. os.remove(self.tmp_file_path)