如何在 Python 中复制一个文件?

272 阅读4分钟

当你在Python中编写脚本时,文件处理可能是一个棘手的领域。有很多情况下,我们需要在Python脚本中处理文件和文件夹。因此,Python 为我们提供了大量的文件操作,当我们遇到这种情况时,会使我们的生活变得更容易。程序员们经常讨论的一个问题是--"如何用Python脚本复制一个文件?"。在本教程中,我们将发现这个问题的答案。

复制操作可以在Python中使用各种可用的模块。不再拖延,让我们深入了解每个模块和各自的方法,使我们能够在Python中执行复制操作(复制一个文件)。

方法1:使用shutil模块

shutil 是Python中的一个模块,它有一些功能来管理对文档、文件及其集合的操作。该模块被普遍用于复制和删除文件。让我们了解一下这个模块中专门用于复制文件的不同方法。

shutil.copyfile()

shutil.copyfile() 方法用于将内容从源文件复制到目的地。如果你没有权限,它会引发一个 。注意 -IOError 源文件应该代表一个文件,目的地可以是目录或文件

语法

shutil.copyfile(source, destination)

例子

# importing the os and shutil modules
import os
import shutil

# The path before copying the file
path = '/home/User/Documents'
print("The path before copying the file:")
print(os.listdir(path))

source = "/home/User/Documents/file.txt"
destination = "/home/User/Documents/file(copy).txt"
# Copying the content
dest = shutil.copyfile(source, destination)

# The path after copying the file
print("The path after copying the file:")
print(os.listdir(path))

输出

The path before copying the file: 
['rashi.png', 'sample.txt', 'file.text', 'copy.cpp']
The path after copying the file:
['rashi.png', 'sample.txt', 'file.text', 'file(copy).txt', 'copy.cpp']

shutil.copy()

shutil.copy() 方法类似于 Unix 中的cp 命令。它意味着,如果目的地是一个文件夹,它将在其中生成另一个文件,其名称与源文件相似,即基名。同样地,这个方法在复制后会将目标文件的内容与源文件同步。

注意: shutil.copy() ,如果你复制的是同一个文件,会抛出SameFileError

语法

shutil.copy(source, destination)

假设目的地是一个目录,只有在目的地可写的情况下,文件才会利用基础文件名被复制到目的地。

例子

# importing the os and shutil modules
import os
import shutil

# The path before copying the file
path = '/home/User/Documents'
print("The path before copying the file:")
print(os.listdir(path))

source = "/home/User/Documents/file.txt"
destination = "/home/User/Desktop"
# Copying the content

dest = shutil.copy(source, destination)
# The path after copying the file
print("The path after copying file:")
print(os.listdir(path))

输出

The path before copying the file: 
['rashi.png', 'sample.txt', 'file.text', 'copy.cpp']
The path after copying file:
['one.txt', 'demo.txt', 'file.txt', 'demo2.py']

**注意:**如果目的地是一个文件,并且如果它存在,它将被替换成源文件,如果不存在,将创建另一个文件。

shutil.copy2()

shutil.copy2() 方法与shutil.copy() 方法类似,但没有什么高级功能。这个方法试图保留文档的元数据。在这个方法中,源文档的内容被复制到目的地。与此同时,源文件的元数据和其他数据也会被复制。

语法

shutil.copy2(source, destination)

下面是一个典型的例子,将展示shutil.copy2() 方法的工作原理。

# importing the os and shutil modules
import os
import shutil

# The path before copying the file
path = '/home/User/Documents'
print("The path before copying the file:")
print(os.listdir(path))
source = "/home/User/Documents/file.txt"

# Copying the metadeta
metadata = os.stat(source)
print("Metadata of source:", metadata)
destination = "/home/User/Desktop"

# Copying the content
dest = shutil.copy2(source, destination)
# The path after copying the file
print("The path after copying file:")
print(os.listdir(path))

# Metadata of destination file
matadata = os.stat(destination)
print("Metadata of destination:", metadata)

输出

The path before copying the file:
['rashi.png', 'sample.txt', 'file.text', 'copy.cpp']
Metadata of source:
os.stat_result(st_mode=33188, st_ino=801113, st_gid=1000, st_size=84, st_mtime=1558866156, st_ctime=1558866156)
The path after copying the file:
['rashi.png', 'sample.txt', 'file.text', 'file(copy).txt', 'copy.cpp']
Metadata of destination:
os.stat_result(st_mode=33188, st_ino=801111, st_gid=1000, st_size= 84, st_mtime=1558866156, st_ctime=1558933947)

方法2:使用os模块

os.popen()

os.popen() 方法用于使用一个命令创建一个管道。它返回一个文件对象,该对象与管道接口。你可以利用它来写或读文件,即'r'或'w'。

语法

os.popen(command[, mode[, bufsize]] )

如果bufsize的值是0,那么,在这一点上,不会发生缓冲。如果bufsize值为1,将发生行缓冲。如果bufsize大于1,将以预先确定的缓冲区大小进行缓冲。对于一个负值,系统将使用默认的大小。

例子

# Importing the os module
import os
os.chdir(r'/home/User/Documents/demo.txt ')
# Setting the file of both source and the destination
source = os.getcwd() + "\source"
destination = os.getcwd() + "\destination"
# Copying the contents from source to destination
os.popen('copy source\demo.txt destination\demo.txt')

注意: os.popen() 方法在Python 2.6中被弃用。作为另一种选择,Python文档鼓励我们利用子进程模块的方法。

方法 3: 使用subprocess模块

在Python中,subprocess模块被用来从我们的应用程序中执行一个新的子进程,并与管道和输入输出相关联,获得它们的返回代码。

subprocess.call()

可以利用子进程模块的**call()**方法来执行作为参数传递的任何命令。返回值将是被执行的命令的结束状态。

语法

subprocess.call(args, stdin = None, stdout = None, stderr = None, shell = False)

这里,args 参数包括 shell 命令。

**注意:**Python文档中提到,使用 shell = True 可以证明是一种安全风险。

例子

# Importing the subprocess module
import subprocess

# Copying the contents from source to destination
status = subprocess.call('copy file.txt demo.txt', shell=True)

上面的例子将把file.txt复制到demo.txt文件中。

总结

在本教程中,我们已经介绍了在 Python 中复制文件的不同方法。我们希望这能提供一些信息。