最推荐使用shutil.copy2()复制文件,因其能保留文件内容、权限及元数据(如修改时间、访问时间),适用于备份与迁移;若目标文件存在,默认会直接覆盖,可通过os.path.exists()预先检查并处理;复制目录则需用shutil.copytree(),支持递归复制及忽略特定文件。

用Python复制文件,最直接且推荐的方式是使用内置的
shutil
shutil.copy()
shutil.copyfile()
shutil.copy2()
在Python中复制文件,我们通常会依赖
shutil
os
核心函数是shutil.copy2()
copy2
import shutil
import os
source_file = "my_document.txt"
destination_file = "backup_document.txt"
# 假设my_document.txt存在
# with open(source_file, "w") as f:
# f.write("这是我的重要文档内容。\n")
# f.write("一些敏感信息,需要保留权限和时间戳。\n")
try:
# 使用shutil.copy2()复制文件,保留元数据
shutil.copy2(source_file, destination_file)
print(f"文件 '{source_file}' 已成功复制到 '{destination_file}',并保留了元数据。")
# 验证一下修改时间是否一致
src_mtime = os.path.getmtime(source_file)
dst_mtime = os.path.getmtime(destination_file)
print(f"源文件修改时间: {src_mtime}")
print(f"目标文件修改时间: {dst_mtime}")
if src_mtime == dst_mtime:
print("修改时间已成功保留。")
else:
print("修改时间未能完全保留,可能与文件系统或操作系统有关。")
except FileNotFoundError:
print(f"错误:源文件 '{source_file}' 不存在。")
except PermissionError:
print(f"错误:没有权限复制文件到 '{destination_file}'。")
except Exception as e:
print(f"复制文件时发生未知错误: {e}")
# 另外两个函数简要提一下:
# shutil.copyfile(src, dst):只复制文件内容,不复制元数据。
# shutil.copy(src, dst):复制文件内容和权限,但不保证复制所有元数据(比如修改时间)。
# 所以,如果你需要最全面的复制,记住用copy2。这是一个非常实际的问题。默认情况下,
shutil.copy()
shutil.copyfile()
shutil.copy2()
立即学习“Python免费学习笔记(深入)”;
我的做法通常有两种:
预先检查并决定行为:在调用复制函数之前,先用
os.path.exists()
import shutil
import os
source_file = "my_document.txt"
destination_file = "backup_document.txt"
if os.path.exists(destination_file):
print(f"目标文件 '{destination_file}' 已存在。")
# 我们可以选择:
# 1. 询问用户 (在交互式脚本中)
# 2. 自动重命名目标文件
# new_destination_file = destination_file + ".bak"
# os.rename(destination_file, new_destination_file)
# print(f"已将现有文件重命名为 '{new_destination_file}'。")
# 3. 直接覆盖 (这是shutil.copy2的默认行为)
print("将直接覆盖现有文件。")
try:
shutil.copy2(source_file, destination_file)
print(f"文件 '{source_file}' 已成功复制到 '{destination_file}'。")
except FileNotFoundError:
print(f"错误:源文件 '{source_file}' 不存在。")
except Exception as e:
print(f"复制文件时发生错误: {e}")利用异常处理:虽然
shutil.copy
FileExistsError
FileExistsError
shutil.copy2
这是个好问题,因为文件和目录在操作系统层面就是不同的实体。
shutil.copy()
shutil.copytree()
shutil.copytree(src, dst, symlinks=False, ignore=None, copy_function=copy2, ignore_dangling_symlinks=False, dirs_exist_ok=False)
src
dst
symlinks
True
False
ignore
.git
__pycache__
copy_function
shutil.copy2
dirs_exist_ok
True
copytree
False
FileExistsError
实现示例:
import shutil
import os
source_dir = "my_project_folder"
destination_dir = "project_backup"
# 假设my_project_folder存在,并有一些文件和子目录
# os.makedirs(os.path.join(source_dir, "sub_dir"), exist_ok=True)
# with open(os.path.join(source_dir, "file1.txt"), "w") as f: f.write("Hello")
# with open(os.path.join(source_dir, "sub_dir", "file2.txt"), "w") as f: f.write("World")
try:
# 复制整个目录
# 注意:如果destination_dir已存在且dirs_exist_ok=False,会报错
shutil.copytree(source_dir, destination_dir, dirs_exist_ok=True)
print(f"目录 '{source_dir}' 已成功复制到 '{destination_dir}'。")
# 举个例子,如何使用ignore参数排除文件
# def ignore_pycache(directory, contents):
# return [c for c in contents if c == '__pycache__' or c.endswith('.pyc')]
# shutil.copytree(source_dir, "project_backup_no_pycache", ignore=ignore_pycache)
# print("目录复制完成,并忽略了__pycache__。")
except FileExistsError:
print(f"错误:目标目录 '{destination_dir}' 已存在。请删除或使用dirs_exist_ok=True。")
except FileNotFoundError:
print(f"错误:源目录 '{source_dir}' 不存在。")
except Exception as e:
print(f"复制目录时发生错误: {e}")这正是
shutil.copy2()
shutil.copy()
shutil.copyfile()
shutil.copyfile(src, dst)
src
dst
shutil.copy(src, dst)
copyfile
st_mode
st_mtime
st_atime
copy2
copy2
shutil.copy2(src, dst)
为什么保留这些元数据很重要?
所以,当你需要确保复制的文件尽可能地与原始文件一致时,毫不犹豫地选择
shutil.copy2()
以上就是python怎么复制一个文件_python文件复制操作实现方法的详细内容,更多请关注php中文网其它相关文章!
python怎么学习?python怎么入门?python在哪学?python怎么学才快?不用担心,这里为大家提供了python速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号