How To Copy A File In Python

In this blog post, we will learn how to copy a file in Python using both the built-in shutil library and a custom function. Copying a file can be useful in various scenarios like making backups or duplicating files for processing.

Using the shutil Library

The shutil library is part of the Python Standard Library, which means it comes pre-installed with Python. It provides a simple way to copy a file using the copy or copy2 function.

Using the copy Function

The syntax for the copy function is:

shutil.copy(src, dst, *, follow_symlinks=True)

Where src is the source file, dst is the destination file, and follow_symlinks is an optional boolean parameter to specify whether to follow symbolic links.

Here’s an example of how to use the copy function:

import shutil

src = "source.txt"
dst = "destination.txt"

shutil.copy(src, dst)

Using the copy2 Function

The syntax for the copy2 function is:

shutil.copy2(src, dst, *, follow_symlinks=True)

The copy2 function is similar to the copy function, but it preserves the file’s metadata (such as timestamps) during the copy. Here’s an example:

import shutil

src = "source.txt"
dst = "destination.txt"

shutil.copy2(src, dst)

Custom Function to Copy a File

If you prefer to create your custom function to copy a file, you can do so using the built-in open function. Here’s an example:

def copy_file(src, dst):
    with open(src, "rb") as source_file:
        with open(dst, "wb") as destination_file:
            destination_file.write(source_file.read())

src = "source.txt"
dst = "destination.txt"

copy_file(src, dst)

In this example, we’re opening the source file in binary mode for reading (rb) and the destination file in binary mode for writing (wb). Then, we read the content of the source file and write it to the destination file.

Conclusion

In this blog post, we learned about two different methods to copy a file in Python: using the built-in shutil library and creating a custom function. Both methods have their use cases, so choose the one that best suits your needs.