file.py 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. import os
  2. from typing import Optional
  3. class File:
  4. @staticmethod
  5. def read_file(file_path: str) -> Optional[str]:
  6. """
  7. 读取文件内容
  8. 参数:
  9. file_path: 文件路径
  10. 返回:
  11. 文件内容字符串,如果出错返回None
  12. """
  13. try:
  14. with open(file_path, 'r', encoding='utf-8') as f:
  15. return f.read()
  16. except Exception as e:
  17. print(f"读取文件 {file_path} 出错: {str(e)}")
  18. return None
  19. @staticmethod
  20. def write_file(file_path: str, content: str) -> bool:
  21. """
  22. 写入内容到文件
  23. 参数:
  24. file_path: 文件路径
  25. content: 要写入的内容
  26. 返回:
  27. 是否成功写入
  28. """
  29. try:
  30. with open(file_path, 'w', encoding='utf-8') as f:
  31. f.write(content)
  32. return True
  33. except Exception as e:
  34. print(f"写入文件 {file_path} 出错: {str(e)}")
  35. return False
  36. @staticmethod
  37. def ensure_directory_exists(dir_path: str) -> bool:
  38. """
  39. 确保目录存在,如果不存在则创建
  40. 参数:
  41. dir_path: 目录路径
  42. 返回:
  43. 是否成功确保目录存在
  44. """
  45. try:
  46. os.makedirs(dir_path, exist_ok=True)
  47. return True
  48. except Exception as e:
  49. print(f"创建目录 {dir_path} 出错: {str(e)}")
  50. return False
  51. # 使用示例
  52. if __name__ == "__main__":
  53. # 测试load_system_prompt
  54. test_content = "这是一个测试文件内容"
  55. File.write_file("test.txt", test_content)
  56. read_content = File.read_file("test.txt")
  57. print(f"读取的文件内容: {read_content}")
  58. # 测试ensure_directory_exists
  59. File.ensure_directory_exists("test_dir")