The shutil
library in Python offers various functions for copying files and directories. In this post, we will examine five methods: shutil.copy
, shutil.copyfile
, shutil.copy2
, shutil.copyfileobj
, and shutil.copytree
. We'll examine their differences and understand their applications through examples.
The shutil.copy
function allows us to copy the contents of a file to another location. Here's a simple code snippet demonstrating its use
import shutil
source = 'source.txt'
destination = 'destination.txt'
shutil.copy(source, destination)
In this example, the content of source.txt
is copied to destination.txt
. If destination.txt
does not exist, it will be created.
Unlike shutil.copy
, shutil.copyfile
only copies the content of the file, ignoring any metadata such as permissions. Here's an example
import shutil
source = 'source.txt'
destination = 'destination.txt'
shutil.copyfile(source, destination)
This code will copy the content from source.txt
to destination.txt
, but without copying any file metadata.
The shutil.copy2
function behaves similarly to shutil.copy
, but it also preserves the original file's metadata, such as timestamps. Here's how it's used
import shutil
source = 'source.txt'
destination = 'destination.txt'
shutil.copy2(source, destination)
The content and metadata from source.txt
are copied to destination.txt
.
The shutil.copyfileobj
function is used to copy the content of a file object to another file object. Here's a practical example
import shutil
with open('source.txt', 'rb') as src, open('destination.txt', 'wb') as dest:
shutil.copyfileobj(src, dest)
This code reads the content from source.txt
and writes it to destination.txt
.
The shutil.copytree
function is used to copy an entire directory tree. Example
import shutil
source_dir = 'source_directory'
destination_dir = 'destination_directory'
shutil.copytree(source_dir, destination_dir)
This code will copy the entire content of source_directory
to destination_directory
.
Function | Copies Content | Copies Permissions | Copies Metadata | Uses File Object | Destination may be Directory |
---|---|---|---|---|---|
shutil.copy | Yes | Yes | No | No | Yes |
shutil.copyfile | Yes | No | No | No | No |
shutil.copy2 | Yes | Yes | Yes | No | Yes |
shutil.copyfileobj | Yes | No | No | Yes | No |
shutil.copytree | Yes | Yes | Yes | No | Yes |
The shutil
library in Python offers diverse functions for copying files and directories. Understanding their differences ensures efficient file management.
shutil.copy
copies content and permissions, while shutil.copy2
also includes metadata like timestamps.shutil.copytree
recursively copies an entire directory tree, including all nested directories and files.symlinks=True
argument in shutil.copytree
to preserve symbolic links.CloneCoding
Innovation Starts with a Single Line of Code!