用Python编写的文件拷贝工具
发布时间:2023-12-04 19:44:01
下面是一个用Python编写的文件拷贝工具的代码示例:
import shutil
def copy_file(source_file, destination_file):
try:
shutil.copy(source_file, destination_file)
print("文件拷贝成功!")
except IOError as e:
print("拷贝文件时出错:", str(e))
if __name__ == "__main__":
source_file = "path/to/source/file.txt"
destination_file = "path/to/destination/file.txt"
copy_file(source_file, destination_file)
上面的代码使用了shutil库中的copy函数来进行文件拷贝操作。shutil.copy(source_file, destination_file)用于将source_file文件复制到destination_file所指定的路径中。
在主函数中,你需要指定你想要拷贝的源文件和目标文件的路径。将source_file替换为你实际的源文件路径,将destination_file替换为你实际的目标文件路径。
运行上面的代码后,它将从源文件路径拷贝文件到目标文件路径,并输出“文件拷贝成功!”。如果在拷贝过程中出现错误,它将捕获IOError异常,并输出错误信息。
注意,你需要确保源文件路径和目标文件路径是有效的,并具有相应文件的读取和写入权限。
你可以根据你的具体需求修改上面的代码,例如添加文件夹拷贝功能,支持多个文件同时拷贝等。
