file_util.py 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123
  1. import os
  2. import shutil
  3. from typing import Optional, List
  4. class FileUtil:
  5. """文件操作工具类"""
  6. @staticmethod
  7. def get_file_extension(filename: str) -> Optional[str]:
  8. """获取文件扩展名
  9. Args:
  10. filename: 文件名
  11. Returns:
  12. 文件扩展名,如果文件没有扩展名返回None
  13. """
  14. _, ext = os.path.splitext(filename)
  15. return ext[1:] if ext else None
  16. @staticmethod
  17. def get_file_size(filepath: str) -> Optional[int]:
  18. """获取文件大小
  19. Args:
  20. filepath: 文件路径
  21. Returns:
  22. 文件大小(字节),如果文件不存在返回None
  23. """
  24. try:
  25. return os.path.getsize(filepath)
  26. except OSError:
  27. return None
  28. @staticmethod
  29. def is_file_exists(filepath: str) -> bool:
  30. """检查文件是否存在
  31. Args:
  32. filepath: 文件路径
  33. Returns:
  34. bool: 文件是否存在
  35. """
  36. return os.path.isfile(filepath)
  37. @staticmethod
  38. def create_directory(dirpath: str) -> bool:
  39. """创建目录
  40. Args:
  41. dirpath: 目录路径
  42. Returns:
  43. bool: 是否创建成功
  44. """
  45. try:
  46. os.makedirs(dirpath, exist_ok=True)
  47. return True
  48. except OSError:
  49. return False
  50. @staticmethod
  51. def list_files(dirpath: str,
  52. recursive: bool = False) -> Optional[List[str]]:
  53. """列出目录下的文件
  54. Args:
  55. dirpath: 目录路径
  56. recursive: 是否递归列出
  57. Returns:
  58. 文件路径列表,如果目录不存在返回None
  59. """
  60. if not os.path.isdir(dirpath):
  61. return None
  62. if recursive:
  63. file_list = []
  64. for root, _, files in os.walk(dirpath):
  65. for file in files:
  66. file_list.append(os.path.join(root, file))
  67. return file_list
  68. else:
  69. return [
  70. f for f in os.listdir(dirpath)
  71. if os.path.isfile(os.path.join(dirpath, f))
  72. ]
  73. @staticmethod
  74. def delete_file(filepath: str) -> bool:
  75. """删除文件
  76. Args:
  77. filepath: 文件路径
  78. Returns:
  79. bool: 是否删除成功
  80. """
  81. try:
  82. os.remove(filepath)
  83. return True
  84. except OSError:
  85. return False
  86. @staticmethod
  87. def copy_file(src: str, dst: str) -> bool:
  88. """复制文件
  89. Args:
  90. src: 源文件路径
  91. dst: 目标文件路径
  92. Returns:
  93. bool: 是否复制成功
  94. """
  95. try:
  96. shutil.copy2(src, dst)
  97. return True
  98. except OSError:
  99. return False