FileManager.py 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. import os
  2. import shutil
  3. class FileManager:
  4. def __init__(self):
  5. pass
  6. @staticmethod
  7. def create_directory(cache_path):
  8. if not os.path.exists(cache_path):
  9. os.makedirs(cache_path)
  10. @staticmethod
  11. def write_in_file(file_path, content):
  12. with open(file_path, "wb") as file_open:
  13. file_open.write(content)
  14. file_open.close()
  15. return not FileManager.file_is_empty(file_path)
  16. @staticmethod
  17. def wipe_cache(cache_path):
  18. shutil.rmtree(cache_path)
  19. @staticmethod
  20. def file_is_empty(file_path):
  21. return os.path.getsize(file_path) == 0
  22. @staticmethod
  23. def remove_file(file_path):
  24. if os.path.exists(file_path):
  25. return os.remove(file_path)
  26. @staticmethod
  27. def is_path_creatable(pathname):
  28. """
  29. `True` if the current user has sufficient permissions to create the passed
  30. pathname; `False` otherwise.
  31. """
  32. dirname = os.path.dirname(pathname) or os.getcwd()
  33. return os.access(dirname, os.W_OK)
  34. @staticmethod
  35. def is_path_exists_or_creatable(pathname):
  36. """
  37. `True` if the passed pathname is a valid pathname for the current OS _and_
  38. either currently exists or is hypothetically creatable; `False` otherwise.
  39. This function is guaranteed to _never_ raise exceptions.
  40. """
  41. try:
  42. return os.path.exists(pathname) or FileManager.is_path_creatable(pathname)
  43. except OSError:
  44. return False