Python Program to Copy a File

Updated on December 6, 2024
Copy a file header image

Introduction

Copying files is a frequent necessity in programming, whether for data backup, modification, or migration processes. Python, with its wide array of built-in libraries and modules, provides several straightforward methods to handle file operations including copying files.

In this article, you will learn how to implement file copying using Python. Various methods including the built-in shutil module and lower-level file handling techniques will be explored through practical examples.

Using the shutil Module

Basic File Copying

  1. Import the shutil module.

  2. Define the source file path and the destination file path.

  3. Use shutil.copy() to copy the file.

    python
    import shutil
    
    source_path = 'source.txt'
    destination_path = 'destination.txt'
    shutil.copy(source_path, destination_path)
    

    Here, shutil.copy() takes the source file and destination file path as arguments and performs the copy operation. This method also preserves the permission bits of the original file.

Copying File with Metadata

  1. To maintain not just the file contents but also metadata such as modification time, use shutil.copy2().

  2. Implement in a similar way as shutil.copy().

    python
    import shutil
    
    source_path = 'source.txt'
    destination_path = 'destination.txt'
    shutil.copy2(source_path, destination_path)
    

    The shutil.copy2() method is similar to shutil.copy() but also copies the file's metadata.

Using Python's Built-in File Handling

Simple File Copying Using Read and Write

  1. Open the source file in read mode.

  2. Open the destination file in write mode.

  3. Read content from the source file and write it to the destination file.

  4. Close both files to release resources.

    python
    with open('source.txt', 'rb') as source_file:
        with open('destination.txt', 'wb') as destination_file:
            destination_file.write(source_file.read())
    

    This code block uses Python's context managers to handle files, ensuring that files are properly closed after the operations. It reads the data in binary mode to handle all types of file contents (not just text).

Conclusion

Copying files in Python can be handled efficiently using various methods. The shutil module provides straightforward functions with additional features like metadata copying, while Python's basic file handling capabilities offer flexibility for custom operations. Use each method based on the requirements of your project, considering factors like file size, type, and whether file metadata needs to be preserved. By integrating these techniques, you enhance your Python code's functionality and robustness in dealing with file operations.