The Wayback Machine - https://web.archive.org/web/20241126181835/https://www.geeksforgeeks.org/python-shutil-copy-method/
Open In App

Python | shutil.copy() method

Last Updated : 09 Jan, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Python3




# Python program to explain shutil.copy() method
   
# importing shutil module
import shutil
 
# Source path
source = "/home/User/Documents/file.txt"
 
# Destination path
destination = "/home/User/Documents/file.txt"
 
# Copy the content of
# source to destination
 
try:
    shutil.copy(source, destination)
    print("File copied successfully.")
 
# If source and destination are same
except shutil.SameFileError:
    print("Source and destination represents the same file.")
 
# If there is any permission issue
except PermissionError:
    print("Permission denied.")
 
# For other errors
except:
    print("Error occurred while copying file.")


Output

Error occurred while copying file.

Shutil module in Python provides many functions of high-level operations on files and collections of files. It comes under Python’s standard utility modules. This module helps in automating process of copying and removal of files and directories.
shutil.copy() method in Python is used to copy the content of source file to destination file or directory. It also preserves the file’s permission mode but other metadata of the file like the file’s creation and modification times is not preserved. 
Source must represent a file but destination can be a file or a directory. If the destination is a directory then the file will be copied into destination using the base filename from source. Also, destination must be writable. If destination is a file and already exists then it will be replaced with the source file otherwise a new file will be created.
 

Syntax: shutil.copy(source, destination, *, follow_symlinks = True)
Parameter: 
source: A string representing the path of the source file. 
destination: A string representing the path of the destination file or directory. 
follow_symlinks (optional) : The default value of this parameter is True. If it is False and source represents a symbolic link then destination will be created as a symbolic link.
Note: The ‘*’ in parameter list indicates that all following parameters (Here in our case ‘follow_symlinks’) are keyword-only parameters and they can be provided using their name, not as positional parameter.
Return Type: This method returns a string which represents the path of newly created file. 
 

Code #1: Use of shutil.copy() method to copy file from source to destination 
 

Python3




# Python program to explain shutil.copy() method
   
# importing os module
import os
 
# importing shutil module
import shutil
 
# path
path = '/home/User/Documents'
 
# List files and directories
# in '/home/User/Documents'
print("Before copying file:")
print(os.listdir(path))
 
 
# Source path
source = "/home/User/Documents/file.txt"
 
# Print file permission
# of the source
perm = os.stat(source).st_mode
print("File Permission mode:", perm, "\n")
 
# Destination path
destination = "/home/User/Documents/file(copy).txt"
 
# Copy the content of
# source to destination
dest = shutil.copy(source, destination)
 
# List files and directories
# in "/home / User / Documents"
print("After copying file:")
print(os.listdir(path))
 
# Print file permission
# of the destination
perm = os.stat(destination).st_mode
print("File Permission mode:", perm)
 
# Print path of newly
# created file
print("Destination path:", dest)


Output: 

Before copying file:
['hrithik.png', 'test.py', 'sample.txt', 'file.text', 'copy.cpp']
File permission mode: 33188

After copying file:
['hrithik.png', 'test.py', 'sample.txt', 'file.text', 'file(copy).txt', 'copy.cpp']
File permission mode: 33188 
Destination path: /home/User/Documents/file(copy).txt

 

Code #2: If destination is a directory 
 

Python3




# Python program to explain shutil.copy() method
   
# importing os module
import os
 
# importing shutil module
import shutil
 
 
# Source path
source = "/home/User/Documents/file.txt"
 
# Destination path
destination = "/home/User/Desktop/"
 
# Copy the content of
# source to destination
dest = shutil.copy(source, destination)
 
# List files and directories
# in "/home / User / Desktop"
print("After copying file:")
print(os.listdir(destination))
 
# Print path of newly
# created file
print("Destination path:", dest)


Output: 

After copying file:
['input.txt', 'GeeksForGeeks', 'output.txt', 'file.txt', 'web.py', 'tree.cpp']
Destination path: /home/User/Desktop/file.txt

 

Code #3: Possible errors while using shutil.copy() method 
 

Python3




# Python program to explain shutil.copy() method
   
# importing shutil module
import shutil
 
 
# If the source and destination
# represents the same file
# 'SameFileError' exception
# will be raised
 
# If the destination is
# not writable
# 'PermissionError' exception
# will be raised
 
 
# Source path
source = "/home/User/Documents/file.txt"
 
# Destination path
destination = "/home/User/Documents/file.txt"
 
# Copy the content of
# source to destination
shutil.copy(source, destination)


Output: 

Traceback (most recent call last):
  File "try.py", line 26, in 
    dest = shutil.copy(source, destination)
  File "/usr/lib/python3.6/shutil.py", line 241, in copy
    copyfile(src, dst, follow_symlinks=follow_symlinks)
  File "/usr/lib/python3.6/shutil.py", line 104, in copyfile
    raise SameFileError("{!r} and {!r} are the same file".format(src, dst))
shutil.SameFileError: '/home/User/Desktop/file.txt' and  '/home/User/Desktop/file.txt'
are the same file

 

Code #4: Handling errors while using shutil.copy() method 
 

Python3




# Python program to explain shutil.copy() method
   
# importing shutil module
import shutil
 
# Source path
source = "/home/User/Documents/file.txt"
 
# Destination path
destination = "/home/User/Documents/file.txt"
 
# Copy the content of
# source to destination
 
try:
    shutil.copy(source, destination)
    print("File copied successfully.")
 
# If source and destination are same
except shutil.SameFileError:
    print("Source and destination represents the same file.")
 
# If there is any permission issue
except PermissionError:
    print("Permission denied.")
 
# For other errors
except:
    print("Error occurred while copying file.")


Output: 

Source and destination represents the same file.

 

Reference: https://docs.python.org/3/library/shutil.html
 

Time complexity : O(N)
Auxiliary space : O(1)



Similar Reads

copy in Python (Deep Copy and Shallow Copy)
In Python, Assignment statements do not copy objects, they create bindings between a target and an object. When we use the = operator, It only creates a new variable that shares the reference of the original object. In order to create "real copies" or "clones" of these objects, we can use the copy module in Python. Syntax of Python DeepcopySyntax:
7 min read
Python | shutil.get_archive_formats() method
Shutil module in Python provides many functions of high-level operations on files and collections of files. It comes under Python’s standard utility modules. This module helps in automating process of copying and removal of files and directories. shutil.get_archive_formats() method in Python is used to get the list of supported formats for archivin
1 min read
Python | shutil.copy2() method
Shutil module in Python provides many functions of high-level operations on files and collections of files. It comes under Python’s standard utility modules. This module helps in automating process of copying and removal of files and directories.shutil.copy2() method in Python is used to copy the content of source file to destination file or direct
4 min read
Python | shutil.get_unpack_formats() method
Shutil module in Python provides many functions of high-level operations on files and collections of files. It comes under Python’s standard utility modules. This module helps in automating process of copying and removal of files and directories. shutil.get_unpack_formats() method in Python is used to get the list of all supported formats available
2 min read
Python | shutil.disk_usage() method
Shutil module in Python provides many functions of high-level operations on files and collections of files. It comes under Python’s standard utility modules. This module helps in automating process of copying and removal of files and directories. shutil.disk_usage() method in Python is to get disk usage statistics about the given path. This method
2 min read
Python | shutil.unregister_unpack_format() method
Shutil module in Python provides many functions of high-level operations on files and collections of files. It comes under Python’s standard utility modules. This module helps in automating process of copying and removal of files and directories. shutil.unregister_unpack_format() method in Python is used to unregister or remove an unpack format fro
2 min read
Python | shutil.unregister_archive_format() method
Shutil module in Python provides many functions of high-level operations on files and collections of files. It comes under Python’s standard utility modules. This module helps in automating the process of copying and removal of files and directories. shutil.unregister_archive_format() method in Python is used to unregister or remove an archive form
2 min read
Python | shutil.copystat() method
Shutil module in Python provides many functions of high-level operations on files and collections of files. It comes under Python’s standard utility modules. This module helps in automating process of copying and removal of files and directories.shutil.copystat() method in Python is used to copy the permission bits, last access time, last modificat
3 min read
Python | shutil.copymode() method
Shutil module in Python provides many functions of high-level operations on files and collections of files. It comes under Python’s standard utility modules. This module helps in automating the process of copying and removal of files and directories.shutil.copymode() method in Python is used to copy the permission bits from the given source path to
2 min read
Python | shutil.disk_usage() method
Shutil module in Python provides many functions of high-level operations on files and collections of files. It comes under Python’s standard utility modules. This module helps in automating process of copying and removal of files and directories. shutil.disk_usage() method tells the disk usage statistics about the given path as a named tuple with t
2 min read
Python | shutil.copytree() method
Shutil module in Python provides many functions of high-level operations on files and collections of files. It comes under Python’s standard utility modules. This module helps in automating process of copying and removal of files and directories. shutil.copytree() method recursively copies an entire directory tree rooted at source (src) to the dest
3 min read
Python | shutil.chown() method
Shutil module in Python provides many functions of high-level operations on files and collections of files. It comes under Python’s standard utility modules. This module helps in automating process of chowning and removal of files and directories.shutil.chown() method in Python is used to change the owner and /or group of the specified path. Syntax
3 min read
Python | shutil.copyfileobj() method
Shutil module in Python provides many functions of high-level operations on files and collections of files. It comes under Python’s standard utility modules. This module helps in automating process of chowning and removal of files and directories.shutil.copyfileobj() method in Python is used to copy the contents of a file-like object to another fil
2 min read
Delete an entire directory tree using Python | shutil.rmtree() method
Shutil module in Python provides many functions of high-level operations on files and collections of files. It comes under Python’s standard utility modules. This module helps in automating the process of copying and removal of files and directories. shutil.rmtree() is used to delete an entire directory tree, path must point to a directory (but not
3 min read
Python | shutil.get_terminal_size() method
Shutil module in Python provides many functions of high-level operations on files and collections of files. It comes under Python’s standard utility modules. This module helps in automating process of copying and removal of files and directories. shutil.get_terminal_size() method tells the size of the terminal window. As terminal is of the two dime
1 min read
Python | shutil.copyfile() method
Shutil module in Python helps automate the process of copying and removing files and directories. It comes under Python’s standard utility modules. Shutil(short for shell utility) module also provides many functions of high-level operations on files and collections of files. What is Shutil.copyfile() method?The shutil.copyfile() method in Python is
4 min read
Python | shutil.which() method
Shutil module in Python provides many functions of high-level operations on files and collections of files. It comes under Python’s standard utility modules. This module helps to automate the process of copying and removal of files and directories. shutil.which() method tells the path to an executable application that would be run if the given cmd
2 min read
Python | shutil.unpack_archive() method
Shutil module in Python provides many functions of high-level operations on files and collections of files. It comes under Python’s standard utility modules. This module helps in automating process of copying and removal of files and directories.shutil.unpack_archive() method in Python is used to unpack an archive file. Syntax: shutil.unpack_archiv
2 min read
Python | shutil.move() method
Shutil module in Python provides many functions of high-level operations on files and collections of files. It comes under Python’s standard utility modules. This module helps in automating the process of copying and removing files and directories. The shutil.move() method moves a file or directory from a source to a destination. It handles directo
2 min read
Shutil Module in Python
Shutil module offers high-level operation on a file like a copy, create, and remote operation on the file. It comes under Python’s standard utility modules. This module helps in automating the process of copying and removal of files and directories. In this article, we will learn this module. Copying Files to another directory shutil.copy() method
8 min read
Difference Between os.rename and shutil.move in Python
When it comes to renaming or moving files and directories, two commonly used methods are os. rename and shutil. move. While both can serve the purpose of renaming and moving, they have distinct differences in terms of functionality and use cases. In this article, we will explore these differences and when to use each of them. Difference Between os.
3 min read
NumPy ndarray.copy() Method | Make Copy of a Array
The ndarray.copy() method returns a copy of the array. It is used to create a new array that is a copy of an existing array but does not share memory with it. This means that making any changes to the original array won't affect the existing array. Example C/C++ Code # Python program explaining # numpy.ndarray.copy() function import numpy as geek x
2 min read
Difference Between Shallow copy VS Deep copy in Pandas Dataframes
The pandas library has mainly two data structures DataFrames and Series. These data structures are internally represented with index arrays, which label the data, and data arrays, which contain the actual data. Now, when we try to copy these data structures (DataFrames and Series) we essentially copy the object's indices and data and there are two
4 min read
Shallow copy vs Deep copy in Pandas Series
The pandas library has mainly two data structures DataFrames and Series. These data structures are internally represented with index arrays, which label the data, and data arrays, which contain the actual data. Now, when we try to copy these data structures (DataFrames and Series) we essentially copy the object's indices and data and there are two
4 min read
Python PIL | copy() method
PIL is the Python Imaging Library which provides the python interpreter with image editing capabilities. PIL.Image.copy() method copies the image to another image object, this method is useful when we need to copy the image but also retain the original. Syntax:Image.copy() Parameters: no arguments Returns:An image object # Importing Image module fr
1 min read
Python List copy() Method
The copy() method in Python is used to create a shallow copy of a list. This means that the method creates a new list containing the same elements as the original list but maintains its own identity in memory. It's especially useful when you want to ensure that changes to the new list do not affect the original list and vice versa. Here's is a basi
3 min read
set copy() in python
The copy() method returns a shallow copy of the set in python. If we use "=" to copy a set to another set, when we modify in the copied set, the changes are also reflected in the original set. So we have to create a shallow copy of the set such that when we modify something in the copied set, changes are not reflected back in the original set. Synt
2 min read
Python Dictionary copy()
Python Dictionary copy() method returns a shallow copy of the dictionary. let's see the Python Dictionary copy() method with examples: Examples Input: original = {1:'geeks', 2:'for'} new = original.copy() // Operation Output: original: {1: 'one', 2: 'two'} new: {1: 'one', 2: 'two'}Syntax of copy() method Syntax: dict.copy() Return: This method does
3 min read
Python | Difference between Pandas.copy() and copying through variables
Pandas .copy() method is used to create a copy of a Pandas object. Variables are also used to generate copy of an object but variables are just pointer to an object and any change in new data will also change the previous data. The following examples will show the difference between copying through variables and Pandas.copy() method. Example #1: Co
2 min read
Python | Ways to Copy Dictionary
Dictionary is a collection which is unordered, changeable and indexed. In Python, dictionaries are written with curly brackets, and they have keys and values. It is widely used in day to day programming, web development, and machine learning. When we simply assign dict1 = dict2 it refers to the same dictionary. Let's discuss a few ways to copy the
3 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg