mytempfile.py 1.2 KB

1234567891011121314151617181920212223242526272829303132333435
  1. import tempfile
  2. import os
  3. import shutil
  4. class MyTempFile:
  5. """
  6. A context manager for creating a temporary file in current directory, copying the content from
  7. a specified file, and handling cleanup operations upon exiting the context.
  8. Usage:
  9. ```python
  10. with MyTempFile(file_path) as temp_file_manager:
  11. # Access the temporary file using temp_file_manager.tmp_file
  12. # ...
  13. # The temporary file is automatically closed and removed upon exiting the context.
  14. ```
  15. Args:
  16. - file_path (str): The path to the file whose content will be copied to the temporary file.
  17. """
  18. def __init__(self, file_path):
  19. self.file_path = file_path
  20. self.tmp_file = None
  21. self.tmp_file_path = None
  22. def __enter__(self):
  23. self.tmp_file = tempfile.NamedTemporaryFile('w', dir='.', delete=False)
  24. self.tmp_file_path = os.path.relpath(self.tmp_file.name, '.')
  25. shutil.copyfile(self.file_path, self.tmp_file_path)
  26. return self
  27. def __exit__(self, exc_type, exc_value, exc_traceback):
  28. self.tmp_file.close()
  29. if os.path.isfile(self.tmp_file_path):
  30. os.remove(self.tmp_file_path)