Python | shutil.copyfileobj () method

File handling | Python Methods and Functions

The shutil.copyfileobj() method in Python is used to copy the contents of a file object to another file object. By default, this method copies data in chunks, and if desired, we can also specify the size of the buffer through the length parameter. 
This method copies the contents of the file from the current file position to the end of the file.

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

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.

Code: using method shutil.copyfileobj () to copy the contents of the source file object to the target file object

Exit :

 Contents of file object copied successfully 


# Python program to explain the shutil.copy method fileobj ()

# shutil module import

import shutil

# Source file

source = 'file.txt'

# Open the source file
# in read mode and
# get the file object

fsrc = open (source, 'r'


# target file

dest = ' file_copy.txt'

# Open the destination file
# in write mode and
# get file object

fdst = open (dest, 'w' )


# Now copy the content
# file object from f1 to f2
# using the shutil.copyfileobj () method
shutil.copyfileobj (fsrc, fdst)

# We can also specify
  # buffer size per pause
# optional length parameter
# like shutil.copyfileobj (fsrc, fdst, 1024)


print ( "Contents of file object copied successfully" )

# Close file objects
f1.close ()
f2.close ()