[파이썬] shutil `shutil.copyfileobj()`: 파일 객체 내용 복사하기

In Python, the shutil module provides a copyfileobj() function which allows you to copy the contents of one file object to another. This can be particularly useful when you want to copy the contents of a file-like object, such as a network socket or a StringIO object, to another file.

Usage

The basic syntax of the copyfileobj() function is as follows:

import shutil

shutil.copyfileobj(src_file, dst_file, length=16*1024)

The function takes three arguments:

Examples

Let’s see a couple of examples to understand how copyfileobj() works.

Example 1: Copying a file-like object to a file

import shutil
from io import BytesIO

# Create a file-like object with some content
src_file = BytesIO(b"This is the content of the source file.")

# Open a destination file in binary mode
with open("destination.txt", "wb") as dst_file:
    shutil.copyfileobj(src_file, dst_file)

In this example, we use the BytesIO class from the io module to create a file-like object src_file with some content. Then, we open a destination file destination.txt using the open() function and pass it as the dst_file argument to copyfileobj(). The content of the src_file will be copied to destination.txt.

Example 2: Copying data from a socket to a file

import shutil
import socket

# Create a socket object
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# Connect to a remote server
sock.connect(("example.com", 80))

# Open a file in binary mode to store the received data
with open("received_data.bin", "wb") as dst_file:
    shutil.copyfileobj(sock.makefile(), dst_file)

In this example, we create a socket object sock and connect it to a remote server. Then, we open a file received_data.bin using the open() function in binary mode. We pass sock.makefile() as the src_file argument to copyfileobj(), which enables us to copy the data received from the socket to the file.

Conclusion

The shutil.copyfileobj() function in the shutil module provides a convenient way to copy the contents of one file-like object to another. It offers flexibility and simplicity when dealing with different types of file-like objects, making it a useful tool in Python file manipulation tasks.