📜  如何在 python 中复制文件(1)

📅  最后修改于: 2023-12-03 15:24:19.852000             🧑  作者: Mango

如何在 Python 中复制文件

在编程中,经常需要复制文件,将文件从一个位置复制到另一个位置,Python 提供了多种方法来实现这一操作。本文将介绍如何使用 Python 实现文件复制。

方法一:使用 shutil 模块的 copy2() 函数

首先,我们可以使用 Python 的 shutil 模块中的 copy2() 函数来实现文件复制。以下是示例代码:

import shutil

src_file = "/path/to/source/file"
dst_dir = "/path/to/destination/directory"

shutil.copy2(src_file, dst_dir)

在这个示例代码中,src_file 是源文件的路径,dst_dir 是目标目录的路径,shutil.copy2() 函数将源文件复制到目标目录。

方法二:使用文件对象的 read() 和 write() 方法

另一种复制文件的方法是使用 Python 中的文件对象的 read() 和 write() 方法。以下是示例代码:

src_file = "/path/to/source/file"
dst_file = "/path/to/destination/file"

with open(src_file, "rb") as fsrc:
    with open(dst_file, "wb") as fdst:
        fdst.write(fsrc.read())

在这个示例代码中,我们打开源文件和目标文件,并使用它们的 read() 和 write() 方法将源文件中的内容复制到目标文件。

方法三:使用 os 模块的系统调用

最后,我们可以使用 Python 的 os 模块的系统调用来复制文件。以下是示例代码:

import os

src_file = "/path/to/source/file"
dst_file = "/path/to/destination/file"

os.system(f"cp {src_file} {dst_file}")

在这个示例代码中,我们可以使用操作系统的 cp 命令来复制源文件到目标文件。

无论使用哪种方法,Python 都提供了多种实现文件复制的方式,让您可以根据实际需求选择最合适的方法。