Python| shutil.copyfileobj() 方法
Python中的Shutil 模块提供了许多对文件和文件集合进行高级操作的功能。它属于 Python 的标准实用程序模块。该模块有助于自动化处理和删除文件和目录。
Python中的shutil.copyfileobj()方法用于将一个类文件对象的内容复制到另一个类文件对象。默认情况下,此方法以块的形式复制数据,如果需要,我们还可以通过长度参数指定缓冲区大小。
此方法将文件内容从当前文件位置复制到文件末尾。
Syntax: shutil.copyfileobj(fsrc, fdst[, length])
Parameters:
fsrc: A file-like object representing the source file to be copied
fdst: A file-like object representing the destination file, where fsrc will be copied.
length (optional): An integer value denoting buffer size.
File-like object are mainly StringIO objects, connected sockets and actual file objects.
Return Type: This method does not return any value.
代码:使用shutil.copyfileobj()方法将源类文件对象的内容复制到目标类文件对象
Python3
# Python program to explain shutil.copyfileobj() method
# importing shutil module
import shutil
# Source file
source = 'file.txt'
# Open the source file
# in read mode and
# get the file object
fsrc = open(source, 'r')
# destination file
dest = 'file_copy.txt'
# Open the destination file
# in write mode and
# get the file object
fdst = open(dest, 'w')
# Now, copy the contents of
# file object f1 to f2
# using shutil.copyfileobj() method
shutil.copyfileobj(fsrc, fdst)
# We can also specify
# the buffer size by passing
# optional length parameter
# like shutil.copyfileobj(fsrc, fdst, 1024)
print("Contents of file object copied successfully")
# Close file objects
f1.close()
f2.close()
Contents of file object copied successfully
参考: https://docs。 Python.org/3/library/shutil.html