How to Copy Files in Python: Methods, Examples and Best Practices

How to Copy Files in Python: Methods, Examples and Best Practices

To copy files in Python, you can use the shutil module which provides a high-level interface for file operations. Here is an example of how to copy a file:

python

import shutil

# source file path
src_file = ‘/path/to/source/file’

# destination file path
dst_file = ‘/path/to/destination/file’

# copy the file
shutil.copy(src_file, dst_file)

In this example, shutil.copy() takes two arguments: the source file path and the destination file path. It copies the contents of the source file to the destination file. If the destination file already exists, it will be overwritten.

If you want to copy a directory and its contents, you can use shutil.copytree():

python

import shutil

# source directory path
src_dir = ‘/path/to/source/directory’

# destination directory path
dst_dir = ‘/path/to/destination/directory’

# copy the directory and its contents
shutil.copytree(src_dir, dst_dir)

In this example, shutil.copytree() takes two arguments: the source directory path and the destination directory path. It recursively copies the entire directory and its contents to the destination directory. If the destination directory already exists, it will raise an error.

Al Mahbub Khan
Written by Al Mahbub Khan Full-Stack Developer & Adobe Certified Magento Developer

Full-stack developer at Scylla Technologies (USA), working remotely from Bangladesh. Adobe Certified Magento Developer.