欢迎访问宙启技术站
智能推送

利用distutils.file_util模块中的copy_file()方法,在Python中实现文件复制操作

发布时间:2024-01-13 02:23:54

在Python中,可以使用distutils.file_util模块中的copy_file()方法来实现文件复制操作。copy_file()方法允许将一个文件从源路径复制到目标路径。下面是一个使用例子,其中演示了如何使用copy_file()方法复制文件。

from distutils.file_util import copy_file

def copy_file_example(source_file, destination_file):
    try:
        copy_file(source_file, destination_file)
        print("文件复制成功!")
    except IOError as e:
        print("文件复制失败:", str(e))

# 源文件路径
source_file = "path/to/source_file.txt"

# 目标文件路径
destination_file = "path/to/destination_file.txt"

# 调用copy_file_example()方法
copy_file_example(source_file, destination_file)

在上面的例子中,首先导入了distutils.file_util模块的copy_file()方法。然后,编写了一个名为copy_file_example()的函数,它接受源文件路径和目标文件路径作为参数。

在copy_file_example()方法中,我们尝试使用copy_file()方法将源文件复制到目标文件。如果复制过程成功完成,将打印"文件复制成功!"。否则,如果出现IO错误,将打印"文件复制失败:",并输出错误消息。

请确保将"path/to/source_file.txt"替换为实际的源文件路径,并将"path/to/destination_file.txt"替换为实际的目标文件路径。

此例子演示了如何使用distutils.file_util模块中的copy_file()方法进行文件复制操作。你可以根据自己的需求修改源文件和目标文件的路径,并在需要复制文件的其他部分调用copy_file_example()方法。