file_io.py 1023 B

1234567891011121314151617181920212223242526272829303132333435363738
  1. import os
  2. from pathlib import Path
  3. from typing import Union
  4. class FileIO:
  5. def __init__(self, path: Union[os.PathLike, str]):
  6. if isinstance(path, str):
  7. path = Path(path)
  8. self.path = path
  9. def read(self): # Returns bytes/str
  10. # We would like to read unicode here, but we cannot, because we are not
  11. # sure if it is a valid unicode file. Therefore just read whatever is
  12. # here.
  13. with open(self.path, 'rb') as f:
  14. return f.read()
  15. def get_last_modified(self):
  16. """
  17. Returns float - timestamp or None, if path doesn't exist.
  18. """
  19. try:
  20. return os.path.getmtime(self.path)
  21. except FileNotFoundError:
  22. return None
  23. def __repr__(self):
  24. return '%s(%s)' % (self.__class__.__name__, self.path)
  25. class KnownContentFileIO(FileIO):
  26. def __init__(self, path, content):
  27. super().__init__(path)
  28. self._content = content
  29. def read(self):
  30. return self._content