FileManager.py 2.6 KB

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