前置
啊,懒得写……
代码
import os
import shutil
import zipfile
def backup_and_delete(base_path, objects_to_delete, backup_path, zip_path):
"""
备份指定目录并删除指定文件或目录。
参数:
base_path: 需要备份的原始目录路径。
objects_to_delete: 需要在备份后从备份目录中删除的文件或目录列表。
backup_path: 备份目录的目标路径。
zip_path: 压缩包的目标路径。
"""
try:
# 检查备份路径是否存在,如果不存在则创建
if not os.path.exists(backup_path):
os.makedirs(backup_path)
# 构建备份目标路径,并确保备份目标不存在时才进行复制
backup_dest = os.path.join(backup_path, os.path.basename(base_path))
if os.path.exists(backup_dest):
shutil.rmtree(backup_dest)
shutil.copytree(base_path, backup_dest)
print(f"已备份 {base_path} 到 {backup_dest}")
except Exception as e:
print(f"备份文件夹失败: {base_path} 到 {backup_path}, 错误: {e}")
return
for obj in objects_to_delete:
obj_path = os.path.join(backup_dest, obj)
# 判断对象是文件还是目录,分别进行删除操作
if os.path.isfile(obj_path):
try:
os.remove(obj_path)
print(f"删除文件: {obj_path}")
except Exception as e:
print(f"删除文件失败: {obj_path}, 错误: {e}")
elif os.path.isdir(obj_path):
try:
shutil.rmtree(obj_path)
print(f"删除文件夹及其内容: {obj_path}")
except Exception as e:
print(f"删除文件夹失败: {obj_path}, 错误: {e}")
else:
print(f"对象不存在: {obj_path}")
try:
# 对备份目录进行压缩打包
shutil.make_archive(zip_path, 'zip', backup_dest)
print(f"已将 {backup_dest} 压缩为 {zip_path}.zip")
except Exception as e:
print(f"压缩文件夹失败: {backup_dest} 到 {zip_path}.zip, 错误: {e}")
# 定义原始目录、删除对象、备份目录、备份后的zip路径
base_path = r"D:\houxiongxiong\codes\GitHub\halo-theme-joe3.0-youzi"
objects_to_delete = [
'.git', '.github', '.idea', 'gradle', '测试',
'.gitignore', 'build.gradle', 'gradlew', 'gradlew.bat', 'LICENSE',
'package.json', 'package-lock.json', 'README.md', 'settings.gradle',
r'templates\assets\js\min\common.min.js.gz',
r'templates\assets\js\min\custom.min.js.gz',
r'templates\assets\js\min\index.min.js.gz',
r'templates\assets\js\min\post.min.js.gz',
r'templates\assets\js\min\utils.min.js.gz'
]
backup_path = r"D:\houxiongxiong\codes\GitHub\backup"
zip_path = r"D:\houxiongxiong\codes\GitHub\halo-theme-joe3.0-youzi"
# 调用函数执行备份和删除操作
backup_and_delete(base_path, objects_to_delete, backup_path, zip_path)
评论区