file_util.py 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125
  1. import json
  2. import os
  3. class FileUtil:
  4. """
  5. 文件操作工具类。
  6. """
  7. @staticmethod
  8. def list_files(folder_path, recursive=False):
  9. """
  10. 列出指定文件夹下的所有文件。
  11. :param folder_path: 文件夹路径
  12. :param recursive: 是否递归遍历子文件夹,默认为 False
  13. :return: 文件路径列表
  14. :raises FileNotFoundError: 如果文件夹不存在
  15. :raises PermissionError: 如果无权限访问文件夹
  16. """
  17. if not os.path.exists(folder_path):
  18. raise FileNotFoundError(f"文件夹未找到: {folder_path}")
  19. if not os.path.isdir(folder_path):
  20. raise ValueError(f"路径不是文件夹: {folder_path}")
  21. files = []
  22. try:
  23. if recursive:
  24. for root, _, filenames in os.walk(folder_path):
  25. for filename in filenames:
  26. files.append(os.path.join(root, filename))
  27. else:
  28. for entry in os.listdir(folder_path):
  29. full_path = os.path.join(folder_path, entry)
  30. if os.path.isfile(full_path):
  31. files.append(full_path)
  32. except PermissionError as e:
  33. raise PermissionError(f"无权限访问文件夹: {e}")
  34. return files
  35. @staticmethod
  36. def read_file(file_path):
  37. """
  38. 从指定文件中读取内容。
  39. :param file_path: 文件路径
  40. :return: 文件内容(字符串)
  41. :raises FileNotFoundError: 如果文件不存在
  42. :raises IOError: 如果读取文件时发生错误
  43. """
  44. try:
  45. with open(file_path, 'r', encoding='utf-8') as file:
  46. return file.read()
  47. except FileNotFoundError:
  48. raise FileNotFoundError(f"文件未找到: {file_path}")
  49. except IOError as e:
  50. raise IOError(f"读取文件时发生错误: {e}")
  51. @staticmethod
  52. def write_file(file_path, content):
  53. """
  54. 将内容写入到指定文件中。
  55. :param file_path: 文件路径
  56. :param content: 要写入的内容(字符串)
  57. :raises IOError: 如果写入文件时发生错误
  58. """
  59. # 确保文件夹存在
  60. directory = os.path.dirname(file_path)
  61. if directory and not os.path.exists(directory):
  62. os.makedirs(directory)
  63. try:
  64. with open(file_path, 'w', encoding='utf-8') as file:
  65. file.write(content)
  66. except IOError as e:
  67. raise IOError(f"写入文件时发生错误: {e}")
  68. @staticmethod
  69. def read_json(file_path):
  70. """
  71. 从指定文件中读取内容并解析为 JSON。
  72. :param file_path: 文件路径
  73. :return: 解析后的 JSON 对象(字典或列表)
  74. :raises FileNotFoundError: 如果文件不存在
  75. :raises IOError: 如果读取文件时发生错误
  76. :raises json.JSONDecodeError: 如果 JSON 解析失败
  77. """
  78. # 检查文件是否存在且非空
  79. if not os.path.exists(file_path):
  80. raise FileNotFoundError(f"文件未找到: {file_path}")
  81. if os.path.getsize(file_path) == 0:
  82. raise ValueError(f"文件内容为空: {file_path}")
  83. try:
  84. with open(file_path, 'r', encoding='utf-8') as file:
  85. return json.load(file)
  86. except FileNotFoundError:
  87. raise FileNotFoundError(f"文件未找到: {file_path}")
  88. except IOError as e:
  89. raise IOError(f"读取文件时发生错误: {e}")
  90. except json.JSONDecodeError as e:
  91. raise json.JSONDecodeError(f"JSON 解析失败: {e.msg}", e.doc, e.pos)
  92. @staticmethod
  93. def write_json(file_path, data):
  94. """
  95. 将 JSON 数据写入到指定文件中。
  96. :param file_path: 文件路径
  97. :param data: 要写入的 JSON 数据(字典、列表等)
  98. :raises IOError: 如果写入文件时发生错误
  99. :raises TypeError: 如果数据无法序列化为 JSON
  100. """
  101. # 确保文件夹存在
  102. directory = os.path.dirname(file_path)
  103. if directory and not os.path.exists(directory):
  104. os.makedirs(directory)
  105. try:
  106. with open(file_path, 'w', encoding='utf-8') as file:
  107. json.dump(data, file, ensure_ascii=False, indent=4)
  108. except IOError as e:
  109. raise IOError(f"写入文件时发生错误: {e}")
  110. except TypeError as e:
  111. raise TypeError(f"数据无法序列化为 JSON: {e}")