Python Copy File To Another Directory
Last Updated : Mar 11, 2024
In this article we will show you the solution of python copy file to another directory, an on-the-shelf computer file consists of a collection of bits and pieces of information or data.
The audio, video, and text files in your computer already belong to several different file types.
The two types of files that we most commonly split are text files and binary files.
Binary data, which can only be read by computers, contains simple text, which can be stored in text files.
In computer terminology, a directory or folder is a collection of files and subdirectories.
Directory subdirectories are contained within other directories. Automated operations can be performed on a wide range of operating system functions.
We will now discuss the idea of how to copy files to another directory in python with an example.
Step By Step Guide On Python Copy File To Another Directory :-
# importing the modules import os import shutil # Providing the folder path origin = 'C:\Users\Dell\Downloads\TC\' target = 'C:\Users\Dell\Downloads\TC TargetPath\' # Fetching the list of all the files files = os.listdir(origin) # Fetching all the files to directory for file_name in files: shutil.copy(origin+file_name, target+file_name) print("files are copied successfully")
- The first step is to import the necessary modules, including os and shutil.
- A path to the source folder where all the files are stored is specified ('origin'), and a path to the destination folder where all the files would be copied ('target').
- In this example, we use the OS module to list all the files in the source folder. It returns a list of all files present in a directory by using the os.listdir() method.
- Once that has been done, we copy the files in the source folder to the target folder using the shutil module. The copying of each file is performed using the shutil.copy(source_file, destination) method.
- The process of iterating through each file in the source folder is based on a for loop. A file is copied from the source folder to the target folder using the shutil.copy method within the loop.
- We print a success message once all of the files have been copied.
Conclusion :-
As a result, we have successfully learned how to copy files to another directory in python with an example.
The purpose of this tutorial has been to demonstrate how we can copy files in Python from one place to another and to become familiar with the different modules that manipulate file systems.
You will also learn how to get a list of files in a directory in Python. Moreover, it is related to this operation and also important.
I hope this article on python copy file to another directory helps you and the steps and method mentioned above are easy to follow and implement.