FileManager.py 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  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. @staticmethod
  38. def file_is_empty(file_path):
  39. """
  40. Check if the file is empty
  41. :param file_path: the path of the file
  42. :return: True if the file is empty, False otherwise
  43. """
  44. return os.path.getsize(file_path) == 0
  45. @staticmethod
  46. def remove_file(file_path):
  47. """
  48. Remove the file locate at the provided `file_path`
  49. :param file_path:
  50. :return: True if the file has been removed successfully, False otherwise
  51. """
  52. if os.path.exists(file_path):
  53. return os.remove(file_path)
  54. @staticmethod
  55. def is_path_creatable(pathname):
  56. """
  57. `True` if the current user has sufficient permissions to create the passed
  58. pathname; `False` otherwise.
  59. """
  60. dirname = os.path.dirname(pathname) or os.getcwd()
  61. return os.access(dirname, os.W_OK)
  62. @staticmethod
  63. def is_path_exists_or_creatable(pathname):
  64. """
  65. `True` if the passed pathname is a valid pathname for the current OS _and_
  66. either currently exists or is hypothetically creatable; `False` otherwise.
  67. This function is guaranteed to _never_ raise exceptions.
  68. .. raises:: OSError
  69. """
  70. try:
  71. return os.path.exists(pathname) or FileManager.is_path_creatable(pathname)
  72. except OSError:
  73. return False