Open In App

How to create a duplicate file of an existing file using Python?

Last Updated : 26 Oct, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will discuss how to create a duplicate of the existing file in Python. Below are the source and destination folders, before creating the duplicate file in the destination folder.

After a duplicate file has been created in the destination folder, it looks like the image below.

For automating of copying and removal of files in Python, shutil module is used. It offers a number of high-level operations on files and collections of files. Using shutil module, we can copy files as well as an entire directory.

Method 1 : Using shutil.copyfile()

It copies the contents of the source file to the destination file in the most efficient way possible. It does not use file objects and also does not copy metadata and permissions.

Syntax : shutil.copyfile(src, dst, *, follow_symlinks=True)

Parameters:

  • src – src here is the complete path of the source file.
  • dest – dest is the complete path of the destination file or directory.The destination location must be writable.
  • follow_symlinks (optional) – The default value of this parameter is True. If it is set to False and src is a symbolic link, a new symbolic link will be created instead of copying the file src points to.

Return Type:- It returns the path of the newly created duplicate file.

Code:

Python3




# Python program to create the duplicate of
# an already existing file
import os
D = r"F:\Dest"
  
# importing the shutil module
import shutil
  
print("Before copying file:")
print(os.listdir(D))
  
# src contains the path of the source file
src = r"C:\Users\YASH\OneDrive\Desktop\small\Src\Test.py"
  
# dest contains the path of the destination file
dest = r"F:\Dest\Test.py"
  
# create duplicate of the file at the destination,
# with the name mentioned
# at the end of the destination path
# if a file with the same name doesn't already
# exist at the destination,
# a new file with the name mentioned is created
path = shutil.copyfile(src,dest)
  
print("After copying file:")
print(os.listdir(D))
  
# print path of the newly created duplicate file
print("Path of the duplicate file is:")
print(path)


Output:

Before copying the file:
['in.txt', 'out.txt']
After copying the file:
['in.txt', 'out.txt', 'Test.py']
Path of the duplicate file is:
F:\Dest\Test.py

Method 2: Using shutil.copy()

It also copies the contents of the source file to the destination file or directory. Unlike copyfile(), shutil.copy() also copies the permissions of the source file.

Syntax : shutil.copy(src, dst, *, follow_symlinks=True)

Parameters:-

  • src – src here is the complete path of the source file.
  • dest – dest is the complete path of the destination file or directory.The destination location must be writable.
  • follow_symlinks (optional) – The default value of this parameter is True. If it is set to False and src is a symbolic link, a new symbolic link will be created instead of copying the file src points to.

Return Type:- It returns the path of the newly created duplicate file.

Code:

Python3




# Python program to create the duplicate of
# an already existing file
import os, stat
D = r"F:\Dest"
  
# importing the shutil module
import shutil
  
print("Before copying file:")
print(os.listdir(D))
  
# src contains the path of the source file
src=r"C:\Users\YASH\OneDrive\Desktop\small\Src\Test.py"
  
# changing the permission(Read, write, and execute 
# by others)
# of the source file
os.chmod(src, stat.S_IRWXO)
  
# dest contains the path of the destination file
dest = r"F:\Dest\Test.py"
  
# create duplicate of the file at the
# destination, with the name mentioned
# at the end of the destination path
# if a file with the same name doesn't
# already exist at the destination,
# a new file with the name mentioned is created
path = shutil.copy(src,dest)
  
# checking the permission of
# the duplicate file to see if the
# permissions have also been copied
# check the permission(Read, write, and execute 
# by others)
# of the duplicate file
print(os.access(path, stat.S_IRWXO))
  
print("After copying file:")
print(os.listdir(D))
  
# print path of the newly created duplicate file
print("Path of the duplicate file is:")
print(path)


Output:

Before copying the file:
['in.txt', 'out.txt']
After copying the file:
False
['in.txt', 'out.txt', 'Test.py']
Path of the duplicate file is:
F:\Dest\Test.py

Method 3: Using shutil.copy2()

It is almost similar to shutil.copy(), except copy2() also attempts to preserve metadata. When follow_symlinks is set to False, and src is a symbolic link, copy2() attempts to copy all metadata from the src symbolic link to the newly-created dst symbolic link.

Syntax : shutil.copy2(src, dst, *, follow_symlinks=True)

Parameters:

  • src – src here is the complete path of the source file.
  • dest – dest is the complete path of the destination file or directory.The destination location must be writable.
  • follow_symlinks (optional) – The default value of this parameter is True. If it is set to False and src is a symbolic link, a new symbolic link will be created instead of copying the file src points to.

Return Type:- It returns the path of the newly created duplicate file.

Code:

Python3




# Python program to create the duplicate of an already 
# existing file
import os
D = r"F:\Dest"
# importing the shutil module
import shutil
  
print("Before copying file:")
print(os.listdir(D))
  
# src contains the path of the source file
src=r"C:\Users\YASH\OneDrive\Desktop\small\Src\Test.py"
  
# dest contains the path of the destination file
dest = r"F:\Dest\Test.py"
  
# using copy2()
path=shutil.copy2(src,dest)
  
# A new duplicate file is added at
# the destination with name we mention
# on the path
print("After copying file:")
print(os.listdir(D))
  
# print path of the newly created duplicate file
print("Path of the duplicate file is:")
print(path)


Output:

Before copying the file:
['in.txt', 'out.txt']
After copying the file:
['in.txt', 'out.txt', 'Test.py']
Path of the duplicate file is:
F:\Dest\Test.py


Similar Reads

How to create multiple CSV files from existing CSV file using Pandas ?
In this article, we will learn how to create multiple CSV files from existing CSV file using Pandas. When we enter our code into production, we will need to deal with editing our data files. Due to the large size of the data file, we will encounter more problems, so we divided this file into some small files based on some criteria like splitting in
3 min read
Add a Column to Existing CSV File in Python
Working with CSV files is a common task in data manipulation and analysis, and Python provides versatile tools to streamline this process. Here, we have an existing CSV file and our task is to add a new column to the existing CSV file in Python. In this article, we will see how we can add a column to a CSV file in Python. Add a New Column to Existi
3 min read
Adding Data into Existing XML File in Python
We are given an XML existing file and our task is to append new data into that existing XML using Python. In this article, we will see how we can append new data to the existing XML using Python. Creating an XML fileIn this example, an XML tree is constructed using the xml.etree.ElementTree module in Python, where child elements with attributes and
3 min read
How to append a new row to an existing csv file?
For writing a CSV file, the CSV module provides two different classes writer and Dictwriter. Here we will discuss 2 ways to perform this task effectively. The First will be 'append a list as a new row to the existing CSV file' and second way is 'Append a dictionary as a new row to the existing CSV file.' First, let's have a look at our existing CSV
3 min read
How to Append Pandas DataFrame to Existing CSV File?
In this discussion, we'll explore the process of appending a Pandas DataFrame to an existing CSV file using Python. Add Pandas DataFrame to an Existing CSV File. To achieve this, we can utilize the to_csv() function in Pandas with the 'a' parameter to write the DataFrame to the CSV file in append mode. Pandas DataFrame to_csv() Syntax Syntax : df.t
3 min read
Create MapType Column from Existing Columns in PySpark
An RDD transformation that applies the transformation function to every element of the data frame is known as a map in Pyspark. There occurs various situations when you have numerous columns and you need to convert them to map-type columns. It can be done easily by using the create_map function with the map key column name and column name as argume
3 min read
Create a new column in Pandas DataFrame based on the existing columns
While working with data in Pandas, we perform a vast array of operations on the data to get the data in the desired form. One of these operations could be that we want to create new columns in the DataFrame based on the result of some operations on the existing columns in the DataFrame. Let's discuss several ways in which we can do that. Given a Da
3 min read
Inserting data into a new column of an already existing table in MySQL using Python
Prerequisite: Python: MySQL Create Table In this article, we are going to see how to Inserting data into a new column of an already existing table in MySQL using Python. Python allows the integration of a wide range of database servers with applications. A database interface is required to access a database from Python. MySQL Connector Python modul
2 min read
Adding new enum column to an existing MySQL table using Python
Prerequisite: Python: MySQL Create Table In this article, we are going to see how to add a new enum column to an existing MySQL table using Python. Python allows the integration of a wide range of database servers with applications. A database interface is required to access a database from Python. MySQL Connector-Python module is an API in python
1 min read
How to append new data to existing XML using Python ElementTree
Extensible Markup Language (XML) is a widely used format for storing and transporting data. In Python, the ElementTree module provides a convenient way to work with XML data. When dealing with XML files, it is common to need to append new data to an existing XML document. This can be achieved efficiently using Python's ElementTree module. What is P
4 min read
Practice Tags :