file_operations.py 1.2 KB

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