备份一个文件夹中的所有子文件夹和文件到另一个目标文件夹中:
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)
-
首先,定义了一个名为
backup_folder
的函数,它接受源文件夹路径和目标文件夹路径作为输入参数。 -
在函数中,首先检查目标文件夹是否存在,如果不存在,则使用
os.makedirs()
创建目标文件夹。 -
然后使用
os.walk()
遍历源文件夹中的所有子文件夹和文件。os.walk()
返回一个生成器,生成每个子文件夹路径、子文件夹列表和文件列表。 -
对于每个子文件夹,使用
os.path.join()
将源文件夹路径和子文件夹名连接起来,得到完整的源文件夹路径source_dir
。然后使用os.path.relpath()
获取相对于源文件夹的相对路径,并使用os.path.join()
将其与目标文件夹路径连接起来,得到完整的目标文件夹路径destination_dir
。如果目标文件夹不存在,则使用os.makedirs()
创建目标文件夹。 -
对于每个文件,使用
os.path.join()
将源文件夹路径和文件名连接起来,得到完整的源文件路径source_file
。然后使用os.path.relpath()
获取相对于源文件夹的相对路径,并使用os.path.join()
将其与目标文件夹路径连接起来,得到完整的目标文件路径destination_file
。 -
在复制文件之前,检查源文件和目标文件的绝对路径是否相同。如果相同,表示源文件和目标文件是同一个文件,则跳过复制操作。
-
使用
shutil.copy2()
函数将源文件复制到目标文件。shutil.copy2()
复制文件,并保留文件的元数据(如修改时间)。复制完成后,打印出复制的文件路径。 -
最后,在调用备份函数之前,需要提供正确的源文件夹路径和目标文件夹路径,并根据实际情况修改这两个变量。
通过这段代码,你可以将一个文件夹及其所有子文件夹和文件备份到另一个目标文件夹中。请确保提供正确的源文件夹路径和目标文件夹路径,以及确保具有适当的文件系统权限来读取源文件夹并写入目标文件夹。