在Python中,可以使用shutil
模块中的copy
函数来复制文件。如果复制的源文件不存在或者复制后的目标文件不存在,可以捕获FileNotFoundError
异常进行处理。
以下是一个示例代码:
import shutil
def copy_file(source_file, destination_file):
try:
shutil.copy(source_file, destination_file)
print("文件复制成功!")
except FileNotFoundError:
print("文件复制失败:源文件或目标文件不存在。")
# 示例用法
source_file = "path/to/source/file.txt"
destination_file = "path/to/destination/file.txt"
copy_file(source_file, destination_file)
请注意,需要将source_file
和destination_file
替换为实际的文件路径。