W3docs

How to copy files

To copy a file in Python, you can use the built-in "shutil" module.

To copy a file in Python, you can use the built-in shutil module. Here is an example of how to copy a file:

Using the shutil module to copy a file in Python

import shutil

# Copy the file "original.txt" to "copy.txt"
shutil.copy("original.txt", "copy.txt")

Note: Use shutil.copy2() instead of shutil.copy() if you need to preserve file metadata like modification times.

<div class="alert alert-info"> Watch a course <span>Watch a video course </span> Python - The Practical Guide</div>

You can also copy files using Python's built-in file I/O functions. Here is an example of how to do that:

Using built-in file I/O to copy a file in Python

# Open the original file and the copy file in binary read and write mode
with open("original.txt", "rb") as original_file, open("copy.txt", "wb") as copy_file:
   # Read the contents of the original file
   contents = original_file.read()
   # Write the contents to the copy file
   copy_file.write(contents)

Both of these methods will create a new file called "copy.txt" that is a copy of the original file "original.txt". For production code, consider wrapping file operations in try...except blocks to handle potential FileNotFoundError or IOError exceptions.