×

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

Method Overloading in Python

Overloading is a capability of a method and operator to behave differently according to the nature of parameters. Overloading is popular because it provides a good number of advantages: Reusability of code.Reduces...

3 minutes read.

Run exec python from PHP

PHP (which is a recursive abbreviation for PHP Hypertext Preprocessor) is one of the most broadly involved web improvement innovations on the planet. PHP code utilized for creating sites and...

4 minutes read.

Hog Descriptor Opencv Python

Python programming language: Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations in a...

3 minutes read.

Python Operators

Operators in Python programming An operator is a symbol that operates on one or more operands. An operand is a value or a variable on which we perform the operation....

5 minutes read.

Python IDE names

Python is one of the most renowned programming languages. It has different execution conditions and a great many compilers to execute the python programs, e.g., PyCharm, PyDev, Jupyter Notebook, Visual...

6 minutes read.

Python String rsplit() method

Python String rsplit() method The string.rsplit() method in Python splits a string into a list, starting from the right. If the "max" parameter is not specified, this method will return the...

1 minute read.

Colors in Python

Adding colour to your visualisations will help them come to life. Even if you know the colours you want to use, picking good ones and putting them into practise might...

4 minutes read.

Assignment Operators in Python

The prime usage of Assignment Operators is to assign values to variables. These are taken into account to do operations on values and variables. There are some special symbols in python...

4 minutes read.

Python enumerate() function

Python enumerate() function The enumerate() function in Python takes a collection (e.g. a tuple) and returns it as an enumerate object. Syntax: enumerate(iterable, start=0) Parameter Iterable:  This parameter represents an iterable object start:    This parameter represents a number defining...

1 minute read.

Bar Plot in Python

A bar chart or bar graph displays categorical data using rectangular bars with heights or lengths proportionate to the values for the data distributed in the dataset. In a bar...

16 minutes 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.

chr() and ord() Functions in Python

Python language contains many built-in functions which we use for many programs to work efficiently. The chr() and ord() are a few built-in functions in Python that are used for...

4 minutes read.

Python isinstance() function

Python isinstance() function The isinstance() function in Python returns a Boolean value ‘True’ if the given object is of the specified type, otherwise it returns False. Syntax isinstance(object, classinfo) Parameter object: It is a required parameter which represents an object. classinfo: This...

1 minute read.

Python input() function

Python input() function The input() function in Python reads a line from input and converts it to a string (stripping a trailing newline). Syntax input([prompt]) Parameter prompt: This function represents a string, depicting a default...

1 minute read.

_name_ in Python

Introduction: The code at level 0 indentation is to be performed when the command to run a Python program is supplied to the interpreter because Python does not have a main() function...

4 minutes read.

How to get current date in python?

How to get current date in python? In Python programming language, date and time are not just a data form, but it is possible to import a method called datetime to operate...

3 minutes read.

Python math.cos and math.acos function

Math.cos() function In Python, the Math module is used for performing the mathematical operations. It includes the math.cos() function that is used for obtaining the cosine value of an angle in...

3 minutes read.

Subprocess Module in Python

What is a Process? Every program will have its respective system state, i.e., the state in which it is running. A program that is in a running state or in a...

7 minutes read.

Python Super function

The super function is used to access and call the methods or functions involved in the parent class during Inheritance. What is Inheritance? The process where the parent class inherits some of...

3 minutes read.

Python List pop() method

Python List pop() method The list.pop() method removes the item at the specified position in the list, and return it. If no index is specified, this method removes and returns the last item in the list. Syntax list.pop([i]) Parameter i:...

1 minute read.