本示例将介绍如何将一个文件的内容复制到另一个文件中,提供两种方式:
示例 1:使用 Python3 内置函数
使用 Python3 内置提供的函数,采用手动方式打开源文件、读取内容、写入目标文件,该示例适合理解文件操作的基础原理:
def copy_file(source_path, target_path):
"""
复制文件:从源文件复制到目标文件
:param source_path: 源文件路径
:param target_path: 目标文件路径
"""
try:
# 打开源文件(只读模式)、目标文件(写入模式)
with open(source_path, 'r', encoding='utf-8') as source_file, \
open(target_path, 'w', encoding='utf-8') as target_file:
# 逐行读取并写入
for line in source_file:
target_file.write(line)
print(f"文件复制成功!\n源文件:{source_path}\n目标文件:{target_path}")
except FileNotFoundError:
print("错误:源文件不存在!")
except Exception as e:
print(f"复制失败:{str(e)}")
# 使用示例
if __name__ == "__main__":
# 替换成你的文件路径
copy_file("source.txt", "target.txt")运行结果:
文件复制成功!
源文件:source.txt
目标文件:target.txt注意,记得在当前目录下面创建 source.txt 文件,并且写入一些内容。
示例 2:使用 shutil 库,简洁高效
下面代码将采用 Python3 内置的 shutil 模块来操作文件,使用 shutil 库代码少、稳定、且支持大文件,实际项目优先用这个。代码如下:
import shutil
def copy_file_shutil(source_path, target_path):
"""
使用 shutil 复制文件(推荐)
支持文本、图片、视频等所有文件类型
"""
try:
# 核心复制语句
shutil.copy2(source_path, target_path)
print(f"文件复制成功!\n源文件:{source_path}\n目标文件:{target_path}")
except FileNotFoundError:
print("错误:源文件不存在!")
except Exception as e:
print(f"复制失败:{str(e)}")
# 使用示例
if __name__ == "__main__":
copy_file_shutil("source.txt", "target.txt")运行结果:
文件复制成功!
源文件:source.txt
目标文件:target.txt