FileManager.py 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. import logging
  2. import os
  3. logging.basicConfig()
  4. logger = logging.getLogger("kalliope")
  5. class FileManager:
  6. """
  7. Class used to manage Files
  8. """
  9. def __init__(self):
  10. pass
  11. @staticmethod
  12. def create_directory(cache_path):
  13. """
  14. Create a directory at the provided `cache_path`
  15. :param cache_path: the path of the directory to create
  16. :type cache_path: str
  17. """
  18. if not os.path.exists(cache_path):
  19. os.makedirs(cache_path)
  20. @staticmethod
  21. def write_in_file(file_path, content):
  22. """
  23. Write contents into a file
  24. :param file_path: the path of the file to write on
  25. :type file_path: str
  26. :param content: the contents to write in the file
  27. :type content: str
  28. .. raises:: IOError
  29. """
  30. try:
  31. with open(file_path, "wb") as file_open:
  32. file_open.write(content)
  33. file_open.close()
  34. return not FileManager.file_is_empty(file_path)
  35. except IOError as e:
  36. logger.error("I/O error(%s): %s", e.errno, e.strerror)
  37. return False
  38. @staticmethod
  39. def file_is_empty(file_path):
  40. """
  41. Check if the file is empty
  42. :param file_path: the path of the file
  43. :return: True if the file is empty, False otherwise
  44. """
  45. return os.path.getsize(file_path) == 0
  46. @staticmethod
  47. def remove_file(file_path):
  48. """
  49. Remove the file locate at the provided `file_path`
  50. :param file_path:
  51. :return: True if the file has been removed successfully, False otherwise
  52. """
  53. if os.path.exists(file_path):
  54. return os.remove(file_path)
  55. @staticmethod
  56. def is_path_creatable(pathname):
  57. """
  58. `True` if the current user has sufficient permissions to create the passed
  59. pathname; `False` otherwise.
  60. """
  61. dirname = os.path.dirname(pathname) or os.getcwd()
  62. return os.access(dirname, os.W_OK)
  63. @staticmethod
  64. def is_path_exists_or_creatable(pathname):
  65. """
  66. `True` if the passed pathname is a valid pathname for the current OS _and_
  67. either currently exists or is hypothetically creatable; `False` otherwise.
  68. This function is guaranteed to _never_ raise exceptions.
  69. .. raises:: OSError
  70. """
  71. try:
  72. return os.path.exists(pathname) or FileManager.is_path_creatable(pathname)
  73. except OSError as e:
  74. logger.error("OSError(%s): %s", e.errno, e.strerror)
  75. return False