bak_config_data.py 2.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. import shutil
  2. import os
  3. def backup_files(file_paths, destination_directory):
  4. # 检查目标目录是否存在,不存在则创建
  5. if not os.path.exists(destination_directory):
  6. os.makedirs(destination_directory)
  7. for source_file_path in file_paths:
  8. # 检查源文件是否存在
  9. if os.path.exists(source_file_path):
  10. # 获取文件名
  11. file_name = os.path.basename(source_file_path)
  12. # 构建目标文件路径
  13. destination_file_path = os.path.join(destination_directory, file_name)
  14. # 检查目标文件是否存在,存在则删除
  15. if os.path.exists(destination_file_path):
  16. os.remove(destination_file_path)
  17. # 拷贝文件,覆盖已存在的文件
  18. shutil.copy2(source_file_path, destination_file_path)
  19. print(f"文件 '{file_name}' 备份到 '{destination_directory}'")
  20. else:
  21. print(f"文件 '{source_file_path}' 没有找到. 跳过.")
  22. def backup_dir(source_path, destination_directory):
  23. # 检查目标目录是否存在,不存在则创建
  24. if not os.path.exists(destination_directory):
  25. os.makedirs(destination_directory)
  26. # 构建目标路径
  27. destination_path = os.path.join(destination_directory, os.path.basename(source_path))
  28. try:
  29. # 检查源路径是文件还是文件夹
  30. if os.path.isfile(source_path):
  31. # 如果是文件,检查目标文件是否存在,存在则删除
  32. if os.path.exists(destination_path):
  33. os.remove(destination_path)
  34. # 使用 shutil.copy2 进行文件拷贝
  35. shutil.copy2(source_path, destination_path)
  36. print(f"文件 '{source_path}' 备份到 '{destination_directory}'")
  37. elif os.path.isdir(source_path):
  38. # 如果是文件夹,检查目标文件夹是否存在,存在则删除
  39. if os.path.exists(destination_path):
  40. shutil.rmtree(destination_path)
  41. # 使用 shutil.copytree 进行文件夹拷贝
  42. shutil.copytree(source_path, destination_path)
  43. print(f"文件夹 '{source_path}' 备份到 '{destination_directory}'")
  44. else:
  45. print(f"Unsupported source type: '{source_path}'")
  46. except Exception as e:
  47. print(f"Error during backup: {e}")
  48. # 获取当前脚本所在的绝对路径
  49. current_directory = os.path.abspath(os.path.dirname(__file__))
  50. # 示例用法
  51. file_paths_to_backup = [
  52. os.path.join(current_directory, "config.json")
  53. ]
  54. dir_path_to_backup = os.path.join(current_directory, "data")
  55. dir_path_to_backup2 = os.path.join(current_directory, "out")
  56. destination_directory_path = os.path.join(current_directory, "backup") # 替换为实际的备份目录路径
  57. backup_files(file_paths_to_backup, destination_directory_path)
  58. backup_dir(dir_path_to_backup, destination_directory_path)
  59. backup_dir(dir_path_to_backup2, destination_directory_path)
  60. print("运行结束")