All TalkersCode Topics

Follow TalkersCode On Social Media - A Social Media Network for developers Join Now ➔

How To Copy A File In Python

Last Updated : Jul 25, 2023

How To Copy A File In Python

In this article we will show you the solution of how to copy a file in python, a source file path is passed as the first parameter, while a destination file path is passed as the second parameter.

During the conversion, the content of the source file is replaced with the content of the destination file.

Additionally, there are copy(), cop2(), and copyfileobj() methods that perform the same task with a few changes in metadata.

Sometimes it comes to mind that you have to copy a file when working with Python.

The objective of this article is to demonstrate how to copy a file in Python using the shutil module and its different methods.

It's possible to manipulate files and directories and perform file and directory operations with the shutil (short for shell utility) module in Python.

We will now discuss the idea of how to copy a file in python with an example.

Step By Step Guide On How To Copy A File In Python :-

# Copy only files not directories
import os
import shutil
def copy_files(src, dst):
    for item in os.listdir(src):
        s = os.path.join(src, item)
        d = os.path.join(dst, item)
        if os.path.isfile(s):
            shutil.copy1(s, d)
copy_files("source_folder", "destination_folder
  1. The necessary modules should be imported: OS and Shutil.
  2. A copy_files function has two parameters, src and dst, representing the source and destination folders, respectively.
  3. With os.listdir(src), you can loop through every item (file and directory) in the source folder.
  4. Create the absolute paths for the source (s) and destination (d) items using os.path.join(src, item) and os.path.join(dst, item).
  5. Check if the current item is a file with os.path.isfile(s).
  6. If it is a file, use shutil.copy 1(s, d) to copy the file from the source to the destination.
  7. If it is a directory, the function skips it and moves to the next item.
  8. The function finishes executing without returning any value.

Conclusion :-

As a result, we have successfully learned how to copy a file in python with an example.

Our discussion of file copying in Python has covered various methods. Hopefully, by now you have a better understanding of how to move files with metadata and without metadata.

As well as comparing the approaches, we also looked at the pros and cons of each.

You should choose the one that meets your goals, so be sure to choose the right one.

I hope this article on how to copy a file in python helps you and the steps and method mentioned above are easy to follow and implement.