Python 如何复制文件

Python 如何复制文件

在现代软件开发中,最常见的活动之一就是通过编程复制文件。在今天的快速教程中,我们将使用shutil模块来介绍几种不同的在Python中传输文件的方法。

shutil是一个Python标准库模块,提供了一系列高级文件操作。就文件复制而言,该库提供了各种选项,可以选择是否复制元数据或文件权限,以及目标是否为目录。它属于Python的基本实用模块之一。该模块有助于文件和目录的自动复制和删除。

shutil.copy

shutil.copy()方法将指定的源文件(不包括元数据)复制到指定的目标文件或目录,并返回新生成文件的路径。src参数可以是字符串或路径类对象。

语法

以下是shutil库中copy方法的语法。

Shutil.copy(source_file, destination_file)

示例1

在这个示例中,我们将使用shutil库将一个文件复制到另一个文件中。

#program to copy a file using python
#importing the python library shutil
import shutil
#copying the file example.txt into example2.txt
shutil.copy('example.txt', 'example2.txt')
print("The file is copied")

输出

以下代码的输出结果如下。

The file is copied

Shutil.copy2()

Shutil.copy2()shutil.copy() 相同,唯一的区别是 copy2() 还尝试保留文件元数据。

语法

shutil库中shutil.copy2方法的语法如下所示。

shutil.copy2(source, destination, *, follow_symlinks = True)

copy2 方法的参数:

  • source − 包含源文件位置的字符串。

  • destination − 包含文件或目录目标路径的字符串。

  • 如果传递 True,则追踪符号链接。 − 默认值为 True。如果为假并且源表示符号链接,则尝试从源符号链接复制所有元数据到新生成的目标符号链接。此功能与平台相关。

  • 返回类型 − 此过程会返回一个新生成文件的路径作为字符串。

示例2

在此示例中,我们将了解 shutil 库中 copy2 方法的工作原理。

#program to copy a file using python
#importing the python library shutil
import shutil
#copying the file example.txt into example2.txt
shutil.copy2('example.txt', 'example2.txt')
print("The file is copied")

输出

以上代码的输出如下所示。

The file is copied

shutil.copyfileobj

shutil.copyfileobj是处理文件对象的方法。该方法基本上是将源文件对象的内容复制到目标文件对象中。您还可以选择与用于传输数据的缓冲区大小相匹配的长度。文件权限不会被保留,目录不能作为目标。元数据不会被复制。

语法

shutil.copyfileobj方法的语法如下。

shutil.copyfileobj(fsrc, fdst[, length])

shutil.copyfileobj的参数如下所示。

  • Fsrc − 代表被复制源文件的类文件对象。

  • Fdst − 称为fdst的文件类对象,代表将fsrc传输到其中的文件。

  • length − 可选的整数,表示缓冲区的大小。

示例3

在这里,我们将理解如何使用shutil库中可用的copyfileobj方法。如上所述,此方法用于将源文件对象的内容复制到目标文件对象。

#program to copy a file using python
#importing the python library shutil
import shutil
#copying the file example.txt into example2.txt
source_file = open('example.txt', 'rb')
dest_file = open('example2.txt', 'wb')
shutil.copyfileobj(source_file, dest_file)
print("The file is copied")

输出

上述代码的输出如下所示。

The file is copied

os.system() 方法

子shell中的 system() 方法允许您立即运行任何操作系统命令或脚本。

命令或脚本必须作为参数传递给 system() 函数。该方法在内部使用标准的 C 库函数。其返回值是命令的退出状态。

语法

os.system(command)

system()方法的参数如下所述。

command - 它是一个字符串类型的参数,用于告诉系统要执行的命令。

示例4

在这个示例中,我们将看到如何使用os.system()方法复制文件。如下所示,我们导入所需的库,然后使用system方法将命令’copy example.txt example2.txt’以字符串的形式传递给系统方法。

#program to copy a file using python
#importing the python library OS
import os
#copying example.txt into example2.txt
os.system('copy example.txt  example2.txt')

输出

上述代码的输出如下所示。

sh: 1: copy: not found

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程