How to create a duplicate file of an existing file using Python?
Last Updated :
26 Oct, 2021
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.
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
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
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 Directory If it Does Not Exist using Python?
In this article, We will learn how to create a Directory if it Does Not Exist using Python. Method 1: Using os.path.exists() and os.makedirs() methods Under this method, we will use exists() method takes path of demo_folder as an argument and returns true if the directory exists and returns false if
2 min read
Change case of all characters in a .txt file using Python
In this article, we will learn how to change the case of all characters present in a text file using Python. We will use Python methods Python upper() to change all characters to upper case, and Python lower() to change all characters to lower case.For example, If we have text file data.txt as shown
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 f
3 min read
Python - How to Check if a file or directory exists
Sometimes it's necessary to verify whether a dictionary or file exists. This is because you might want to make sure the file is available before loading it, or you might want to prevent overwriting an already-existing file. In this tutorial, we will cover an important concept of file handling in Pyt
5 min read
How to move all files from one directory to another using Python ?
In this article, we will see how to move all files from one directory to another directory using Python. Â In our day-to-day computer usage we generally copy or move files from one folder to other, now let's see how to move a file in Python: This can be done in two ways:Using os module.Using shutil m
2 min read
Create an empty file using Python
File handling is a very important concept for any programmer. It can be used for creating, deleting, and moving files, or to store application data, user configurations, videos, images, etc. Python too supports file handling and allows users to handle files i.e., to read and write files, along with
3 min read
Copy all files from one directory to another using Python
Copying files from one directory to another involves creating duplicates of files and transferring them from one folder to another. This is helpful when organizing files, backing them up, or moving them to different locations on your computer. Letâs explore various methods to do this efficiently.Usi
2 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 effici
4 min read
How to create filename containing date or time in Python
Prerequisite: DateTime module In this article, we are going to see how to create filenames with dates or times using Python. For this, we will use the DateTime module. First, import the module and then get the current time with datetime.now() object. Now convert it into a string and then create a f
2 min read
Django - How to Create a File and Save It to a Model's FileField?
Django is a very powerful web framework; the biggest part of its simplification for building web applications is its built-in feature of handling file uploads with FileField. Images, documents, or any other file types, Django's FileField makes uploading files through our models easy. In this article
4 min read