Easily Copy File Using Python

In this journey of learning the python programming, let’s take a step ahead and learn some new concepts. Almost everyone here is pretty aware of file handling operations in python or at least heard of that. But besides that, do you know that python also provides us the programming interface to copy files within your system. So, today in this article, we will discuss Copying File Using Python Programming Language. For this, we will use the Copyfile() method. So, Let’s get started.

Copy file Using Shutil Module in Python

CopyFile method is defined in the shutil module of python, which offers several high levels of operations on files. The module provides the functionality of copying files and removing files using python. However, we will only focus on copying a file. And for this purpose, we will use different available methods in the shutil module, such as copyfile() method, copy() method, copy2() method.

Installation and Syntax

The shutil module is built-in python and didn’t require any explicit installation. So let’s go with the syntax.

Method 1: shutil.copyfile()

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

Copyfile() methods consist of the following arguments in which the first two is positional argument and the rest after “*” is keyword argument which means we have to specify its name.

  • src : This arguments specifies the source of the file which we want to copy. It contains the complete path of the file and should be passed as first argument.
  • dst : This is the second argument of the method and specifies the destination of the file and hence requires complete path.
  • follow_symlinks : This argument specifies that if the source path is a link, then it new link is generated rather than than copying the file. However, its default value is True which will copy the file to destination.

Example 1: Copying the File

Once you understand the syntax, let’s see some examples to understand it.

import shutil
import os

# Specifying path to source file
src = 'C:\\Users\\Rishav Raj\\OneDrive\\Documents\\PythonPool\\CopyFile Method\\Source\\src.txt'
# Specifying path of destination directory
dst = 'C:\\Users\\Rishav Raj\\OneDrive\\Documents\\PythonPool\\CopyFile Method\\Destination\\file.txt'
# Checking all files in Destination folder before copying
print(os.listdir('C:\\Users\\Rishav Raj\\OneDrive\\Documents\\PythonPool\\CopyFile Method\\Destination'))

shutil.copyfile(src,dst)
# Checking all files in Destination folder after copying   
print(os.listdir('C:\\Users\\Rishav Raj\\OneDrive\\Documents\\PythonPool\\CopyFile Method\\Destination'))

Output:

[]
['file.txt']

So, in the above example, we first imported the required library. After that, we have specified the source and destination paths. Then we checked all the available files in the destination folder, which returns an empty list, meaning no file is present there. After that, we called the copyfile() method to copy the file. Then we again checked the available files present in the destination folder, which returned a list having the file name we specified, which means the file is copied successfully.

Method 2 : shutil.copy() Method

This method is used when we have to copy a file from a source to a destination file or directory. It is slightly different from the above method as it constrains us to specify the file name also in the directory. However, if we specify the destination directory only, it will copy the file with the same name in that directory. Let’s see the example.

Example 2:

import shutil
import os

# Specifying path to source file
src = 'C:\\Users\\Rishav Raj\\OneDrive\\Documents\\PythonPool\\CopyFile Method\\Source\\src.txt'
# Specifying path of destination directory
dst = 'C:\\Users\\Rishav Raj\\OneDrive\\Documents\\PythonPool\\CopyFile Method\\Destination\\'
# Checking all files in Destination folder before copying
print(os.listdir('C:\\Users\\Rishav Raj\\OneDrive\\Documents\\PythonPool\\CopyFile Method\\Destination'))

shutil.copy(src,dst)
# Checking all files in Destination folder after copying   
print(os.listdir('C:\\Users\\Rishav Raj\\OneDrive\\Documents\\PythonPool\\CopyFile Method\\Destination'))

Output:

['file.txt']
['file.txt', 'src.txt']

Method 3: Using shutil.copy2() method

So, as in the above case, we are copying the file from source to destination, and it is happening successfully, but the thing to note there is that it does not copy the metadata of the source file and the destination file. Using this method, we can also carry the metadata in the variable and use it in our program. Let’s see an example to understand that.

Example 3:

import shutil
import os

# Specifying path to source file
src = 'C:\\Users\\Rishav Raj\\OneDrive\\Documents\\PythonPool\\CopyFile Method\\Source\\src.txt'
# Specifying path of destination directory

# checking metadata before copying
metadata = os.stat(src) 
print("Metadata:", metadata, "\n") 
dst = 'C:\\Users\\Rishav Raj\\OneDrive\\Documents\\PythonPool\\CopyFile Method\\Destination\\'
# Checking all files in Destination folder before copying
print(os.listdir('C:\\Users\\Rishav Raj\\OneDrive\\Documents\\PythonPool\\CopyFile Method\\Destination'))

shutil.copy2(src,dst)
# Checking all files in Destination folder after copying   
print(os.listdir('C:\\Users\\Rishav Raj\\OneDrive\\Documents\\PythonPool\\CopyFile Method\\Destination'))
# checking metadata after copying
metadata = os.stat(dst) 
print("Metadata:", metadata, "\n") 

Output:

Metadata: os.stat_result(st_mode=33206, st_ino=3659174697811557, st_dev=754595617, st_nlink=1, st_uid=0, st_gid=0, st_size=0, st_atime=1641231548, st_mtime=1640758747, st_ctime=1641231548) 
['file.txt', 'src.txt']
['file.txt', 'src.txt']
Metadata: os.stat_result(st_mode=16895, st_ino=7881299348471393, st_dev=754595617, st_nlink=1, st_uid=0, st_gid=0, st_size=0, st_atime=1642063317, st_mtime=1642063146, st_ctime=1641231548) 

Method 4: Using copyfileobj() method

This is another available method in the shutil module. It also copies a file from the source file to the destination file. In this method, we also need to mention the destination file’s name in the path to copy the file. However, this method is slightly different. In this method, we first open the source file in the read byte mode, and then we have to open the destination file in write byte mode. Once we are done with opening the file, we use the copyfileobj() to copy the content from the source to the destination. Let’s see an example.

import shutil
import os

# Specifying path to source file and opening it
src = 'C:\\Users\\Rishav Raj\\OneDrive\\Documents\\PythonPool\\CopyFile Method\\Source\\src.txt'
src_open = open(src,'rb')
# Specifying path of destination directory and opening it
dst = 'C:\\Users\\Rishav Raj\\OneDrive\\Documents\\PythonPool\\CopyFile Method\\Destination\\dst.txt'
dst_open = open(dst,'wb')
# Checking all files in Destination folder before copying
print(os.listdir('C:\\Users\\Rishav Raj\\OneDrive\\Documents\\PythonPool\\CopyFile Method\\Destination'))

shutil.copyfileobj(src_open,dst_open)
# Checking all files in Destination folder after copying   
print(os.listdir('C:\\Users\\Rishav Raj\\OneDrive\\Documents\\PythonPool\\CopyFile Method\\Destination'))

Output:

['dst.txt', 'file.txt', 'src.txt']

Errors while using Copy()/Copy2()/Copyfile() method

However, we encounter different errors while copying the file. Let see some of them.

Example 4: Same File Error

If we specify the source and destination path the same, it will raise the Same File Error. However, if we change the file name only, it will copy that.

import shutil
import os

# Specifying path to source file
src = 'C:\\Users\\Rishav Raj\\OneDrive\\Documents\\PythonPool\\CopyFile Method\\Source\\src.txt'
# Specifying path of destination directory
dst = 'C:\\Users\\Rishav Raj\\OneDrive\\Documents\\PythonPool\\CopyFile Method\\Source\\src.txt'

shutil.copyfile(src,dst)

Output:

Traceback (most recent call last):
  File "C:/Users/Rishav Raj/OneDrive/Documents/PythonPool/CopyFile Method/cpy.py", line 9, in <module>
    shutil.copyfile(src,dst)
  File "C:\Users\Rishav Raj\AppData\Local\Programs\Python\Python310\lib\shutil.py", line 234, in copyfile
    raise SameFileError("{!r} and {!r} are the same file".format(src, dst))
shutil.SameFileError: 'C:\\Users\\Rishav Raj\\OneDrive\\Documents\\PythonPool\\CopyFile Method\\Source\\src.txt' and 'C:\\Users\\Rishav Raj\\OneDrive\\Documents\\PythonPool\\CopyFile Method\\Source\\src.txt' are the same file

Example 5: Python Copy File and Rename

So, in the above case, we can avoid the error by copying the file with another name or changing the path. In the first example, we have seen how we can specify the directory path in which we want to copy. In this example, we have to make a change, and that is at the end of the path, we should change the file’s name. We are going to change it from src.txt to rename.txt.

import shutil
import os

# Specifying path to source file
src = 'C:\\Users\\Rishav Raj\\OneDrive\\Documents\\PythonPool\\CopyFile Method\\Source\\src.txt'
# Specifying path of source directory and renaming the file
dst = 'C:\\Users\\Rishav Raj\\OneDrive\\Documents\\PythonPool\\CopyFile Method\\Source\\rename.txt'

shutil.copyfile(src,dst)

print(os.listdir('C:\\Users\\Rishav Raj\\OneDrive\\Documents\\PythonPool\\CopyFile Method\\Source'))

Output:

['src.txt','rename.txt']

Example 6: Permission Denied Error

However, if the destination path is a folder, not a file, it raises the permission error. So, we need to specify the complete path of the destination. The previous version raises a Directory error, which meant the same. In another case, if the user doesn’t;t have permission to copy the files, it raises the same error.

import shutil
import os

# Specifying path to source file
src = 'C:\\Users\\Rishav Raj\\OneDrive\\Documents\\PythonPool\\CopyFile Method\\Source\\src.txt'
# Specifying path of destination directory
dst = 'C:\\Users\\Rishav Raj\\OneDrive\\Documents\\PythonPool\\CopyFile Method\\Destination'
# Checking all files in Destination folder before copying
print(os.listdir('C:\\Users\\Rishav Raj\\OneDrive\\Documents\\PythonPool\\CopyFile Method\\Destination'))

shutil.copyfile(src,dst)
# Checking all files in Destination folder after copying   
print(os.listdir('C:\\Users\\Rishav Raj\\OneDrive\\Documents\\PythonPool\\CopyFile Method\\Destination'))

Output:

Traceback (most recent call last):
  File "C:/Users/Rishav Raj/OneDrive/Documents/PythonPool/CopyFile Method/cpy.py", line 11, in <module>
    shutil.copyfile(src,dst)
  File "C:\Users\Rishav Raj\AppData\Local\Programs\Python\Python310\lib\shutil.py", line 256, in copyfile
    with open(dst, 'wb') as fdst:
PermissionError: [Errno 13] Permission denied: 'C:\\Users\\Rishav Raj\\OneDrive\\Documents\\PythonPool\\CopyFile Method\\Destination'

Method 5: Python Copy File using OS module

Example 7: Copying file using system() method of OS module

Besides using the shutil module, we can also copy the OS module’s file. There are two available methods for doing that, i.e., popen() method and system() method. We have to pass the command along with the source file name and destination file in both methods. The “cp” command is used for Unix/Linux users and the copy command for windows users. Let’s see an example for each.

import os

os.chdir('C:\\Users\\Rishav Raj\\OneDrive\\Documents\\PythonPool\\CopyFile Method\\Source')
print(os.getcwd())
os.system('copy src.txt dst2.txt')

Output:

C:\Users\Rishav Raj\OneDrive\Documents\PythonPool\CopyFile Method\Source
        1 file(s) copied.

Example 8: Copying file using popen() method of OS module

import os

os.chdir('C:\\Users\\Rishav Raj\\OneDrive\\Documents\\PythonPool\\CopyFile Method\\Source')
print(os.getcwd())
os.popen('copy src.txt dst3.txt')

Output:

C:\Users\Rishav Raj\OneDrive\Documents\PythonPool\CopyFile Method\Source

Method 6: Python Copy file using Subprocess Module

So, as similar to the OS module, we can also copy the file using the SUbprocess module. We will use the call() method inside the module. The syntax is similar to the system function. Let’s see the example.

import subprocess,os

os.chdir('C:\\Users\\Rishav Raj\\OneDrive\\Documents\\PythonPool\\CopyFile Method\\Source')
print(os.getcwd())
status = subprocess.call('copy src.txt dst4.txt', shell=True)

Output:

C:\Users\Rishav Raj\OneDrive\Documents\PythonPool\CopyFile Method\Source
        1 file(s) copied.

FAQs on Python Copy File

Q1) How to make a python file copy itself then execute the other copy once?

You can use the following block of code to do that.

import shutil
import subprocess
import os
import random
print("hello world")
new_file_name = str(random.randint(1, 10000)) + ".py" shutil.copy(__file__, new_file_name) subprocess.call((new_file_name), shell=True)

Q2) How to use ansible to copy files without the modern python version?

You can do it in the following way.

---
- hosts: M
tasks:
- name: generate key pair
shell: ssh-keygen -b 2048 -t rsa -f /root/.ssh/id_rsa -q -N /dev/null
args: creates: /root/.ssh/id_rsa

- name: test public key
shell: ssh-keygen -l -f /root/.ssh/id_rsa.pub
changed_when: false

- name: retrieve public key
shell: cat /root/.ssh/id_rsa.pub
register: master_public_key
changed_when: false
- hosts: SLAVES
tasks:
- name: add master public key to slaves
authorized_key:
user: root
key: "{{ hostvars['M'].master_public_key.stdout }}"

Conclusion

So, today in this article, we learned about copying files in python. For that, we have seen different methods in the shutil module. Besides that, we have also seen OS module and Subprocess module methods for copying the file. We have also seen various examples to understand it more clearly.

After that, we looked at some possible errors while copying the file. We should avoid ourselves to be in any such situation that raises the error and have to be more careful while handling the directories to copy the files. I hope this article has helped you. Thank You.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments