【Python】用shutil模块备份文件夹及子文件夹的所有文件到指定目标目录文件夹中。

备份一个文件夹中的所有子文件夹和文件到另一个目标文件夹中:

import os
import shutil

def backup_folder(source_folder, destination_folder):
    # 创建目标文件夹
    if not os.path.exists(destination_folder):
        os.makedirs(destination_folder)
    
    # 遍历源文件夹中的所有子文件夹和文件
    for root, dirs, files in os.walk(source_folder):
        for dir_name in dirs:
            source_dir = os.path.join(root, dir_name)
            destination_dir = os.path.join(destination_folder, os.path.relpath(source_dir, source_folder))
            if not os.path.exists(destination_dir):
                os.makedirs(destination_dir)
        
        for file_name in files:
            source_file = os.path.join(root, file_name)
            destination_file = os.path.join(destination_folder, os.path.relpath(source_file, source_folder))
            
            # 检查源文件和目标文件是否相同
            if os.path.abspath(source_file) == os.path.abspath(destination_file):
                continue
            
            shutil.copy2(source_file, destination_file)
            print(f"复制文件: {source_file} -> {destination_file}")

# 调用备份函数
source_folder = "源文件夹路径"
destination_folder = "目标文件夹路径"
backup_folder(source_folder, destination_folder)
  1. 首先,定义了一个名为 backup_folder 的函数,它接受源文件夹路径和目标文件夹路径作为输入参数。

  2. 在函数中,首先检查目标文件夹是否存在,如果不存在,则使用 os.makedirs() 创建目标文件夹。

  3. 然后使用 os.walk() 遍历源文件夹中的所有子文件夹和文件。os.walk() 返回一个生成器,生成每个子文件夹路径、子文件夹列表和文件列表。

  4. 对于每个子文件夹,使用 os.path.join() 将源文件夹路径和子文件夹名连接起来,得到完整的源文件夹路径 source_dir。然后使用 os.path.relpath() 获取相对于源文件夹的相对路径,并使用 os.path.join() 将其与目标文件夹路径连接起来,得到完整的目标文件夹路径 destination_dir。如果目标文件夹不存在,则使用 os.makedirs() 创建目标文件夹。

  5. 对于每个文件,使用 os.path.join() 将源文件夹路径和文件名连接起来,得到完整的源文件路径 source_file。然后使用 os.path.relpath() 获取相对于源文件夹的相对路径,并使用 os.path.join() 将其与目标文件夹路径连接起来,得到完整的目标文件路径 destination_file

  6. 在复制文件之前,检查源文件和目标文件的绝对路径是否相同。如果相同,表示源文件和目标文件是同一个文件,则跳过复制操作。

  7. 使用 shutil.copy2() 函数将源文件复制到目标文件。shutil.copy2() 复制文件,并保留文件的元数据(如修改时间)。复制完成后,打印出复制的文件路径。

  8. 最后,在调用备份函数之前,需要提供正确的源文件夹路径和目标文件夹路径,并根据实际情况修改这两个变量。

通过这段代码,你可以将一个文件夹及其所有子文件夹和文件备份到另一个目标文件夹中。请确保提供正确的源文件夹路径和目标文件夹路径,以及确保具有适当的文件系统权限来读取源文件夹并写入目标文件夹。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值