shutil.copyfile()
这个函数只能复制文件,不能复制文件夹,也就是说如果要复制的目标文件夹不存在,该函数不会自动创建,所以在调用这个函数前需要先做个判断:
file_dir = os.path.dirname(dst_path)
if not os.path.exists(file_dir):
os.makedirs(file_dir)
shutil.copyfile(src_path, dst_path)
也可以用os.makedirs()
方法来创建目录:
import shutil
import os
# 源文件路径
source_file = '/path/to/source/file.txt'
# 目标目录路径
target_directory = '/path/to/target/directory/'
# 确保目标目录存在,如果不存在则创建
os.makedirs(target_directory, exist_ok=True)
# 复制文件到目标目录
shutil.copy(source_file, target_directory)
shutil.copy()
函数会将源文件复制到指定的目标目录下。
我们也可以使用 shutil.copy2()
函数来保留文件的元数据(如权限、创建时间等),或者使用 shutil.copyfile()
函数来复制文件内容而不保留元数据。