Copy Files in Python

We have several ways to copy a file using Python. To be precise, there are a total of nine unique functions in Python that we can use to copy a file. In this article, we will learn how to use those functions and their differences. This helps in choosing the right function for the right situation.

Get Paths of Source and Destination Files in Python

All functions that copy files in Python need at least two arguments. A path of the file that we want to copy and a path of the directory where we want to create the copy of the file.

Getting the path of a source file in Python

1. To get the path of the source file, we first need to open the file in the Finder.

Copy Files in Python

2. Right-click on the file that we want to copy. This opens a context menu.

Copying Files in Python

3. Press and hold the option key on the keyboard. This shows a few extra options in the context menu.

Path of source file in Python

4. While holding the option key, click on the option, “Copy ‘filename’ as Pathname” and the path of the file will be copied.

Getting the path of a destination file in Python

To get the path of the destination directory, we first need to open the directory in the Finder and follow the same steps that we followed earlier to copy the source file.

By using the paths that we got, we can use various functions in Python to copy a file. Let us start with the shutil module.

Shutil Module in Python

Shutil is the most common module for copying files with Python. To copy a file, Shutil has the following functions.

1. Copyfile(src, dst)

To copy a file using copyfile(), we need to pass two arguments. src is the string containing the path of the source file directory and dst is the string representing the path of the destination file. It returns a string containing the path of the destination file.

Example on using copyfile() in Python

import shutil
import os

path = '/Users/apple/PythonGeeks/'

src = path + 'lemonade'
dst = path + 'lemonade2'

print(f"Before copying\n{os.listdir(path)}")

print(shutil.copyfile(src, dst))

print(f"After copying\n{os.listdir(path)}")

Output

Before copying
[‘lemonade’]
/Users/apple/PythonGeeks/lemonade2
After copying
[‘lemonade2′,’lemonade’]

In the above code example, Python copied the file lemonade and pasted it with the name lemonade2.

Python raises SameFileError if both src and dst are the same.

Example on using copyfile() in Python

import shutil

path = '/Users/apple/PythonGeeks/'

src = path + 'lemonade'
dst = path + 'lemonade'

print(shutil.copyfile(src, dst))

Output

shutil.SameFileError: ‘/Users/apple/PythonGeeks/lemonade’ and ‘/Users/apple/PythonGeeks/lemonade’ are the same file

Python raises IsADirectoryError when we forget to give the file name.

Example on using copyfile() in Python

import shutil

path = '/Users/apple/PythonGeeks/'

src = path + 'lemonade'
dst = path

print(shutil.copyfile(src, dst))

Output

IsADirectoryError: [Errno 21] Is a directory: ‘/Users/apple/PythonGeeks/’

2. copy(src, dst)

It works similarly to copyfile(). It takes two arguments: the path of a source file, and the path of a destination file. It returns a string containing the path of the destination file.

It raises SameFileError if both src and dst are the same. Unlike copyfile(), we can pass only a directory as the dst argument. It creates a file with the same name as src in the passed directory.

In addition to copying content, copy() also copies the permission of the source file. It internally calls copyfile() and copymode() functions.

Example on using copy() in Python

import shutil
import os

path = '/Users/apple/PythonGeeks/'

src = path + 'lemonade'
dst = path + 'lemonade2'

print(f"Before copying\n{os.listdir(path)}")

print(shutil.copy(src, dst))

print(f"After copying\n{os.listdir(path)}")

Output

Before copying
[‘lemonade’]
/Users/apple/PythonGeeks/lemonade2
After copying
[‘lemonade2′,’lemonade’]

3. copy2(src, dst)

It works similarly to copy(). It takes two arguments path of the source file and the path of the destination file and returns a string containing the path of the destination file. It raises the same errors as the copy() function.

In addition to copying content and permissions, copy2() also copies the metadata of the source file. It internally calls copyfile() and copystat() functions.

Example on using copy2() in Python

import shutil
import os

path = '/Users/apple/PythonGeeks/'

src = path + 'lemonade'
dst = path + 'lemonade2'

print(f"Before copying\n{os.listdir(path)}")

print(shutil.copy2(src, dst))

print(f"After copying\n{os.listdir(path)}")

Output

Before copying
[‘lemonade’]
/Users/apple/PythonGeeks/lemonade2
After copying
[‘lemonade2′,’lemonade’]

4. copyfileobj(fsrc, fdst)

It is a bit different from the previous functions. We need to pass the file descriptor of the source file and the file descriptor of the destination file as src and dst respectively. The source file should be opened in readable ‘r’ mode and the destination file should be opened in writable ‘w’ mode. If we are reading the source file, then the copying starts from the position where we stopped reading. It has no return value.

Example on using copyfileobj() in Python

import shutil
import os

path = '/Users/apple/PythonGeeks/'

src = path + 'lemonade'
dst = path + 'lemonade2'

fsrc = open(src, 'r')
fdst = open(dst, 'w')

print(f"Before copying\n{os.listdir(path)}")
print(shutil.copyfileobj(fsrc, fdst))
print(f"After copying\n{os.listdir(path)}")

Output

Before copying
[‘lemonade2′,’lemonade’]
None
After copying
[‘lemonade2′,’lemonade’]

Copyfile() vs copy() vs copy2() vs copyfileobj() in Python

Functions Copies Content Copies Permissions Copies Metadata Can pass a directory as dst Can pass a file descriptors
copyfile Yes No No No No
copy Yes Yes No Yes No
copy2 Yes Yes Yes Yes No
copyfileobj Yes No No No yes
  • Since copyfile() function copies only content, it is faster than copy() and copy2() functions.
  • The copy2() function copies everything from the source file including permissions and metadata.

OS Module in Python

To copy a file using the OS module, we can use the following functions.

1. popen(command[, mode[. bufsize]])

To copy a file, we need to pass a single argument, a string containing the command we use to copy, the path of the source file, and the path of the destination file separated by space. The command is ‘copy’ for Windows and ‘cp’ for Linux/Unix.

Example on using popen() in Python

import os

path = '/Users/apple/PythonGeeks/'

src = path + 'lemonade'
dst = path + 'lemonade2'

print(f"Before copying\n{os.listdir(path)}")
os.popen(f"cp {src} {dst}")
print(f"After copying\n{os.listdir(path)}")

Output

Before copying
[‘lemonade’]
After copying
[‘lemonade2′,’lemonade’]

2. system(command)

We use system() to run shell commands directly from the Python environment. To copy a file, we need to pass a string containing the command, the path of the source file, and the path of the destination file separated by space. We need to use the command ‘copy’ for Windows and the command ‘cp’ for Linux/Unix operating systems.

Example on using system() in Python

import os

path = '/Users/apple/PythonGeeks/'

src = path + 'lemonade'
dst = path + 'lemonade2'

print(f"Before copying\n{os.listdir(path)}")

os.system(f"cp {src} {dst}")  # For Linux/Unix

print(f"After copying\n{os.listdir(path)}")

Output

Before copying
[‘lemonade’]
After copying
[‘lemonade2′,’lemonade’]

Subprocess in Python

Subprocess has the following functions to copy a file.

1. call()

To copy a file using call() function, we need to pass a positional argument and a keyword argument. The positional argument should be a string containing the command, the path of the source file, and the path of the destination file separated by space. We need to pass the boolean True to the keyword argument shell. The commands are ‘copy’ and ‘cp’ for windows and Linux/Unix respectively.

Example on using call() in Python

import os
import subprocess

path = '/Users/apple/PythonGeeks/'

src = path + 'lemonade'
dst = path + 'lemonade2'

print(f"Before copying\n{os.listdir(path)}")
subprocess.call(f"cp {src} {dst}", shell=True)
print(f"After copying\n{os.listdir(path)}")

Output

Before copying
[‘lemonade’]
After copying
[‘lemonade2′,’lemonade’]

2. check_output()

Similar to the call() function, we need to pass a positional argument, a string with command and paths of both source file and destination file, and a keyword argument shell.

Example on using check_output() in Python

import os
import subprocess

path = '/Users/apple/PythonGeeks/'

src = path + 'lemonade'
dst = path + 'lemonade2'

print(f"Before copying\n{os.listdir(path)}")
subprocess.check_output(f"cp {src} {dst}", shell=True)
print(f"After copying\n{os.listdir(path)}")

Output

Before copying
[‘lemonade’]
After copying
[‘lemonade2′,’lemonade’]

Threading Module

We can also copy a file with the threading module by using the Thread() function.

1. Thread()

This function copies the file asynchronously and needs another module shutil to copy a file. We need to pass two keyword arguments target and args. It has no return value.

Example on using Thread() in Python

import os
import threading
import shutil

path = '/Users/apple/PycharmProjects/DataFlair/'

src = path + 'lemonade'
dst = path + 'lemonade2'

print(f"Before copying\n{os.listdir(path)}")

print(threading.Thread(target=shutil.copy2, args=[src,dst]).run())

print(f"After copying\n{os.listdir(path)}")

Output

Before copying
[‘lemonade’]
None
After copying
[‘lemonade2′,’lemonade’]

Python Interview Questions on Copying Files in Python

Q1. Write a program to copy the file file.txt using the os module.

Ans 1. Complete code is as follows:

import os
os.system('cp file.txt file_copy.txt')
print("File copied")

Output

File copied

Q2. Write a program to copy the file file.txt using the threading module.

Ans 2. Complete code is as follows:

import threading
import shutil
threading.Thread(target=shutil.copy, args=['file.txt', 'file_copy.txt']).run()
print("File copied")

Output

File copied

Q3. Write a program to copy a file file.txt using the subprocess module.

Ans 3. Complete code is as follows:

import subprocess
subprocess.check_output('cp file.txt file_copy.txt', shell=True)
print("File copied")

Output

File copied

Q4. Write a program to copy a file including the metadata and permissions using the shutil module.

Ans 4. Complete code is as follows:

import shutil
shutil.copy2('file.txt', 'file_copy.txt')
print("File copied")

Output

File copied

Q5. Write a program to copy a file without permission and metadata using the shutil module.

Ans 5. Complete code is as follows:

import shutil
shutil.copyfile('file.txt', 'file_copy.txt')
print("File copied")

Output

File copied

Quiz on Copy files in Python

Conclusion

In this article, we learned various ways to copy a file using Python. We also discussed the differences between those functions to understand when to use which functions.

If you have any further queries, please feel free to leave them in the comments area.

Did you like our efforts? If Yes, please give PythonGeeks 5 Stars on Google | Facebook

Leave a Reply

Your email address will not be published. Required fields are marked *