file_operations.py 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. # --coding:utf-8--
  2. '''
  3. 文件操作
  4. '''
  5. import os
  6. import shutil
  7. from loguru import logger
  8. from shutil import copyfile
  9. def save_file(file: bytes, filename):
  10. '''
  11. bytes保存文件
  12. :param file:
  13. :param filename:
  14. :return:
  15. '''
  16. try:
  17. with open(filename, "wb") as fw:
  18. fw.write(file)
  19. fw.close()
  20. return True
  21. except Exception as e:
  22. logger.warning("保存pdf失败-->%s" % e)
  23. return False
  24. def generate_directory(dir: str) -> bool:
  25. '''
  26. :param dir:
  27. :return:
  28. '''
  29. try:
  30. if not os.path.exists(dir):
  31. os.makedirs(dir)
  32. os.chmod(dir, 0o777)
  33. except Exception:
  34. return False
  35. return True
  36. def del_directory(dir: str):
  37. if os.path.exists(dir):
  38. shutil.rmtree(dir)
  39. def file_copy(source_path: str, target_path: str):
  40. """
  41. 文件copy到目标文件夹
  42. :param source_path: 文件原路径
  43. :param target_path: 目标文件夹
  44. :return:
  45. """
  46. try:
  47. copyfile(source_path, target_path)
  48. except IOError as e:
  49. logger.warning("Unable to copy file. %s" % e)
  50. return False
  51. return True