×

Copying a file from one folder to Another with Python

In this article, we shall discuss copying a file from one folder to another using python functions. A file is a collection of data or information stored on a computer. As we already know, there are different types of files, like audio, video, and text files. These text files are taken in a binary format by a computer. While working with files in the python programming language, we call files as directories, and a file present inside another file is called a subdirectory. Now let us see a few file operations done by python.

File operations using python:

Python contains many methods to perform file or folder operations. We use the OS module, one of the in-built modules of python. This module has various functions used for adding and deleting folders or files, retrieving the data from the files, changing the file location, searching for a file location, and many more operations. To have access to all these functions, we first have to import the module by using the below command

import os

after importing the module, we will use the listdir() method to access the files and fetch their data.

Similar to the OS module, we also use another module called shutil which also provides all types of file operation functions. In addition, it gives the user an option to copy or delete files. To import the shutil module, we use the below commands

import shutil
shutil.submodule_name(arguments passed) 

In this module, we have functions like shutil.copy(), shutil.copy2(), and shutil.copytree() to copy files from one directory to another directory. Now let us know how we can work with these functions to copy files.

By shutil.copy() operation:

With this function, the file is copied from the source to the destination or target folder. But the permission mode of the file is preserved, and the metadata of the file, such as the date of creation and modification, will not be preserved. The syntax of this shutil.copy() method is as follows

shutil.copy(origin, target)

Where origin states the current location of the file and target refers to the destination folder where the file is pasted.

By shutil.copy2() operation:

This method is the same as the shutil.copy() method, but the only difference between this and that method is the shutil.copy() method won't preserve the metadata, but in this method, even the metadata is also preserved along with all other data. Even the execution of this method is similar to the shutil.copy() method, but the fetching way of the directory is different. We give the command for this method as follows

shutil.copy2(origin+file_name, target+file_name)

now let us look at an example code using the shutil.copy() method:

Code:

# importing the modules
import os
import shutil
# giving the folder path
origin = 'C:\Users\hp\OneDrive\Desktop\hello\'
target = 'C:\Users\hp\OneDrive\Desktop\java\'


# Fetching the list of files
files = os.listdir(origin)


# Fetching all the files to a directory
for file_name in files:
   shutil.copy(origin+file_name, target+file_name)
print("copied required Files successfully")

Output:

$ python test.py
copied required Files successfully

Explanation:

In this code, we first imported the required modules and then gave the folder paths of the origin and target folders to copy the file. Then we gave a command for fetching the required file and used the shutil.copy() function. At last, we gave a statement to acknowledge that the file had been copied. And after execution of this code, you will find the required output.

By shutil.copytree() method:

This method moves files, and it also moves all the sub-files if present in it. With this, both the source and the destination contain the files. So, the string must include the names of both parameters. The syntax for this method is as follows

shutil.copytree(origin, target)

After using this method, we get an output where we can see the changes made after the execution where the file name changes to the name, we mentioned in the target file.

Conclusion:

With this, we get to cover the process of copying a file from one folder to another folder using the python function. In this, we learned about the basic file structure and operations. To work with python, we discussed two different modules used to file operations. And finally, we saw a few techniques from python modules with an example code for proper understanding.


Related Topics

Python Bitwise Operators

When used with variables and objects in an expression, operators are tokens that carry out calculations. The variables and items to which the computation is applied are known as operands....

5 minutes read.

Sort a dataframe based on a column in Python

Sorting the dataframe based on a column requires pandas which is An open-source library called Python Pandas is described as offering high-performance data processing in Python. For both professionals and...

4 minutes read.

Anaconda in Python 3

What is Anaconda in Python 3? Anaconda is an open-source package combining Python and R programming languages used for data analytics and processing data. It consists of a huge number of...

4 minutes read.

Sort Dictionary in Python

Dictionaries In Python, a dictionary is an unordered collection or set of data types that enable of store data in an unordered key-value/pair. The key is stored alongside with value. Dictionary contains key:...

4 minutes read.

Word frequency Python

Word frequency Python In this tutorial, we will write the Python program to count the occurrence of a word (word frequency) in a given sentence. We will learn all the approaches...

5 minutes read.

Android apps for coding in python

Nowadays, it is the generation of smartphones. The world can be seen and acknowledged with a single click on your mobile phone. Everyone uses mobile phones to do any work,...

9 minutes read.

Python issubclass() Function

Python issubclass() Function The issubclass() function in Python returns a boolean value ‘True’ if the given object is a subclass of classinfo, else it returns False. Syntax issubclass(class, classinfo) Parameter class: It is a required parameter which represents a tuple...

1 minute read.

Python List copy() method

Python List copy () method The list.copy () method returns a shallow copy of the list. Syntax list.copy() Parameter NA Return This function returns the copy for the given list. Example 1 # Python program explaining # the list.copy() method # passing the...

1 minute read.

Python Graph

Python Graph: In Computer Science and Mathematics, a Graph is a pictorial representation of a group of objects or elements where some elements are connected using the links. A graph...

5 minutes read.

Python String isdigit() method

Python String isdigit() method The string.isdigit() method returns a boolean value true if all characters in the string are digits else for any other value it returns false. Syntax string.isdigit() Parameter NA Return This method returns a...

2 minutes read.

How to Reverse a number in Python?

In Python, conditional statements can be combined with the list() method, slice() method, recursion() method, and other predefined techniques to generate reverse logical functions. The reverse() method is the most...

7 minutes read.

What is a Script in Python

Have you ever heard that Python is a scripting language? Or when people address a Python program file as a script? Besides programming, script generally means "a written story for...

3 minutes read.

Ternary operators in python

Starting from Python version 2.5, ternary operators are also known as Conditional operators. Using these operators, we can evaluate any problem based on a condition. It is an alternative and...

4 minutes read.

Python Set clear() Method

Python Set clear() Method The set.clear() method removes all the elements from the set. Syntax set.clear() Parameter NA Return None Example 1 # Python program explaining # the set.clear() method # initializing the set fruits = {"watermelon", "banana", "apple"} # printing the set...

2 minutes read.

Python Dictionary fromkeys() method

Python Dictionary fromkeys() method The dictionary.fromkeys() method in Python creates a new dictionary from the given sequence of elements and returns a dictionary with the specified keys and values. Syntax dictionary.fromkeys(sequence[, value]) Parameter sequence- This...

1 minute read.

Python Dictionary popitem() method

Python Dictionary popitem() method The dictionary.popitem() method in Python removes the item that was last inserted into the dictionary. Syntax dictionary.popitem() Parameter NA Return This method returns an arbitrary element (key, value) pair from the given dictionary...

1 minute read.

Sys Module in Python

What are Modules? The Modules are the kind of files that contain Python statements and definitions. The module is known by the name of the file followed by the suffix “.py”....

5 minutes read.

Python Variable Scope with Local & Non-local Examples

This article will examine Python's global, local and non-local variables and show you how to use them to write code without problems. Let's quickly review what a variable in Python is...

8 minutes read.

Joint Plot in Python

Introduction to Joint plots: The joint plot is the finest approach to evaluate both the specific distribution of each variable and also the connection between the two variables. Three different plots make...

4 minutes read.

Python Static Method

Introduction to methods that are majorly used in Python: Class MethodsInstance MethodsStatic Methods Before going to the in-depth concept of Static Methods, let us briefly discuss Class Methods and Instance Methods. Class Methods The...

4 minutes read.