SoFunction
Updated on 2025-03-10

Summary of 9 ways to copy files in Python

There are many "ready-to-eat" modules in Python (such as os, subprocess and shutil) to support file I/O operations. In this article, you will see some special methods to implement file copying in Python. Let's start learning these nine different methods to implement Python copy file operations.

Before you start, you must understand why it is so important to know the best way to copy files in Python. This is because file I/O operations are performance-intensive and often reach bottlenecks. This is why you should choose the best method based on the design of your application.

Some programs that share resources tend to copy files in blocking mode, while others may wish to execute asynchronously. For example — use threads to copy files or start a separate process to implement it. Another thing to consider is the portability of the platform. This means you should know the target operating system (Windows/Linux/Mac OS X, etc.) that you want to run.

There are 9 ways to copy files in Python:

  • shutil copyfile() method
  • shutil copy() method
  • shutil copyfileobj() method
  • shutil copy2() method
  • os popen method
  • os system() method
  • threading Thread() method
  • subprocess call() method
  • subprocess check_output() method

Copyfile() method

This method will copy the source content to the destination location only if the target is writable. If you do not have write permissions, an IOError exception will be caused.

It opens the input file for reading and ignores its file type. Next, it won't process special files in any different way, nor will it copy them into new special files.

The Copyfile() method uses the following low-level function copyfileobj(). It takes file names as parameters, opens them and passes the file handle to copyfileobj(). There is an optional third parameter in this method, which you can use to specify the buffer length. It then opens the file and reads the chunk of the specified buffer size. However, the default is to read the entire file at once.

copyfile(source_file, destination_file)

Here are the key points about the copyfile() method.

It copies the source content to the target file.

If the target file is not written, the copy operation will cause an IOError exception.

If the source and target files are the same, it will return a SameFileError.

However, if the target file has a different name before, the copy will overwrite its contents.

If the target is a directory, which means that this method will not be copied to the directory, then Error 13 will occur.

It does not support copying files such as character or block drivers and pipelines.

# Python Copy File - Sample Code

from shutil import copyfile
from sys import exit

source = input("Enter source file with full path: ")
target = input("Enter target file with full path: ")

# adding exception handling
try:
   copyfile(source, target)
except IOError as e:
   print("Unable to copy file. %s" % e)
   exit(1)
except:
   print("Unexpected error:", sys.exc_info())
   exit(1)

print("\nFile copy done!\n")

while True:
   print("Do you like to print the file ? (y/n): ")
   check = input()
   if check == 'n':
       break
   elif check == 'y':
       file = open(target, "r")
       print("\nHere follows the file content:\n")
       print(())
       ()
       print()
       break
   else:
       Continue

Copy() method

copyfile(source_file, [destination_file or dest_dir])

The copy() method functions similar to the "cp" command in Unix. This means that if the target is a folder, then it will create a new file in it that has the same name (base name) as the source file. In addition, this method synchronizes the target file permissions to the source file after copying the contents of the source file.

import os
import shutil

source = 'current/test/'
target = '/prod/new'

assert not (source)
target = (target, (source))

# create the folders if not already exists
(target)

# adding exception handling
try:
   (source, target)
except IOError as e:
   print("Unable to copy file. %s" % e)
except:
   print("Unexpected error:", sys.exc_info())

copy() vs copyfile() :

copy() can also set permission bits when copying content, while copyfile() copies only copy only data.

If the target is a directory, copy() will copy the file, and copyfile() will fail with Error 13.

Interestingly, the copyfile() method uses the copyfileobj() method during implementation, while the copy() method uses the copyfile() and copymode() functions in turn.

In Potion-3, it is obvious that copyfile() will be a little faster than copy() because the latter will have an additional task (Permission reserved).

Copyfileobj() method

This method copies the file to the target path or file object. If the target is a file object, then you need to close it after calling copyfileobj() . It also assumes an optional parameter (buffer size) that you can use to set the buffer length. This is the number of bytes saved in memory during copying. The default size used by the system is 16KB.

from shutil import copyfileobj
status = False
if isinstance(target, string_types):
   target = open(target, 'wb')
   status = True
try:
   copyfileobj(, target, buffer_size)
finally:
   if status:
       ()

Copy2() method

Although the function of the copy2() method is similar to copy(). But it can get access and modification times added in the metadata when copying the data. Copying the same file will cause a SameFileError exception.

copy() vs copy2() :

copy() can only set permission bits, while copy2() can also use timestamps to update file metadata.

copy() calls copyfile() and copymode() inside the function, while copy2() calls copystat() to replace copymode().

Popen() method

from shutil import *
import os 
import time
from  import basename

def displayFileStats(filename):
   file_stats = (basename(filename))
   print('\tMode    :', file_stats.st_mode)
   print('\tCreated :', (file_stats.st_ctime))
   print('\tAccessed:', (file_stats.st_atime))
   print('\tModified:', (file_stats.st_mtime))

('test')

print('SOURCE:')
displayFileStats(__file__)

copy2(__file__, 'testfile')

print('TARGET:')
displayFileStats((() + '/test/testfile'))

This method creates a pipeline that sends or accepts commands. It returns an open file object connected to the pipeline. You can use it for reading or writing based on file opening mode, such as ‘r’ (default) or ‘w’.

(command[, mode[, bufsize]])

mode – it can be 'r' (default) or 'w'

Bufsize – If its value is 0, then there will be no buffering. If it is set to 1, line buffering occurs when accessing the file. If you provide a value greater than 1, buffering will occur when the buffer size is specified. However, for negative values, the system will adopt the default buffer size.

For Windows systems:

import os
('copy  ')

For Linux systems:

import os
('cp  ')

System() method

This is the most common way to run any system commands. Using the system() method, you can call any command in the subshell. Internally, the method calls the C language standard library functions.

This method returns the exit status of the command.

For Windows systems:

import os
('copy  ') 

For Linux systems:

import os
('cp  ')

7. Copy files using asynchronous thread library

If you want to copy files asynchronously, use the following method. Here, we use Python's threading module to copy operations in the background.

When using this method, make sure to use locking to avoid locking. This may happen if your application uses multiple threads to read/write files.

import shutil
from threading import Thread

src=""
dst=""

Thread(target=, args=[src, dst]).start()

8. Copy files using the Call() method of Subprocess

The Subprocess module provides a simple interface to handle child processes. It allows us to start a child process, connect to the child process's input/output/error pipeline, and retrieve the return value.

The subprocess module is designed to replace older modules and functions such as – , *, *, popen2.*

It uses the call() method to call the system command to execute user tasks.

import subprocess

src=""
dst=""
cmd='copy "%s" "%s"' % (src, dst)

status = (cmd, shell=True)

if status != 0:
    if status < 0:
        print("Killed by signal", status)
    else:
        print("Command failed with return code - ", status)
else:
    print('Execution of %s passed!\n' % cmd)

9. Copy the file using the Check_output() method in subprocess

Using the Check_output() method in subprocess, you can run external commands or programs and capture their output. It also supports pipelines.

import os, subprocess

src=(() + "/")
dst=(() + "/")
cmd='copy "%s" "%s"' % (src, dst)

status = subprocess.check_output(['copy', src, dst], shell=True)

print("status: ", ('utf-8'))

This is the end of this article about 9 methods for copying Python files. For more related contents of Python copy files, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!