FileManager.py 1.7 KB

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