file_util.py 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. import os
  2. import random
  3. import time
  4. from pathlib import Path
  5. import requests
  6. import urllib3
  7. from send2trash import send2trash
  8. def create_dir(dir_path):
  9. dir_path = Path(dir_path)
  10. if not dir_path.exists():
  11. dir_path.mkdir(parents=True, exist_ok=True)
  12. def file_to_trash(path):
  13. print(f"移动文件或目录:【{path}】到回收站")
  14. send2trash(path)
  15. def file_is_exist(path) -> bool:
  16. return Path(path).exists()
  17. def download_file(url, local_path, max_retries=3, check_file_exists=True):
  18. """下载文件并确保成功"""
  19. urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
  20. if check_file_exists and file_is_exist(local_path):
  21. print(f"文件 {local_path} 已经存在")
  22. return
  23. for attempt in range(max_retries):
  24. try:
  25. response = requests.get(url, stream=True, timeout=10, verify=False)
  26. response.raise_for_status()
  27. os.makedirs(os.path.dirname(local_path), exist_ok=True)
  28. with open(local_path, 'wb') as f:
  29. for chunk in response.iter_content(chunk_size=8192):
  30. f.write(chunk)
  31. print(f"下载成功: {url} -> {local_path}")
  32. return
  33. except Exception as e:
  34. # print(f"下载失败 (尝试 {attempt + 1}/{max_retries}): {url} -> {local_path} \n 错误: {e}")
  35. time.sleep(random.uniform(1, 3))
  36. pass
  37. print(f"最终失败: {url}")