How Do I Copy a File in Python?

File handling can be a tricky area to deal with while you are scripting in Python. There are numerous occasions wherein we need to work with files and folders from within the Python script. Thus, Python facilitates us with numerous file operations that makes life easier for us when we come across such situations. One of the commonly discussed questions among programmers is – “How to copy a File using a Python script?”. In this tutorial we will discover the answer to this question.

The copy operation can be used in Python using the various modules available. Without further delay, let us dive into each module and the respective methods that will enable us to perform the copy operation (copying a file) in Python.

Method 1: Using The shutil Module

The shutil is a module in Python that has few functions to manage operations on documents, files, and their collections. The module is popularly used to copy and remove files. Let us learn about the different methods of this module that are specifically used for copying a file.

shutil.copyfile()

shutil.copyfile() method in Python is used to copy the content to the destination from the source. It raises an IOError if you don’t have permission. Note that – the source should represent a document and the destination can be either directory or file. 

Syntax: 
shutil.copyfile(source, destination)

Example:

# importing the os and shutil modules
import os
import shutil

# The path before copying the file
path = '/home/User/Documents'
print("The path before copying the file:")
print(os.listdir(path))

source = "/home/User/Documents/file.txt"
destination = "/home/User/Documents/file(copy).txt"
# Copying the content
dest = shutil.copyfile(source, destination)

# The path after copying the file
print("The path after copying the file:")
print(os.listdir(path))

Output:

The path before copying the file: 
['rashi.png', 'sample.txt', 'file.text', 'copy.cpp']
The path after copying the file:
['rashi.png', 'sample.txt', 'file.text', 'file(copy).txt', 'copy.cpp']

shutil.copy()   

The shutil.copy() method is similar to the cp command in Unix. It implies that if the destination is a folder, it’ll make another file inside it with a similar name, i.e. basename as the source document. Likewise, this method will synchronize the contents of the destination document with the source after copying.

Note: shutil.copy() throws the SameFileError in case you are copying the same file.

Syntax: 
shutil.copy(source, destination)

Assuming the destination is a directory, the file will be copied into the destination utilizing the base file name only if the destination is writable.

Example:

# importing the os and shutil modules
import os
import shutil

# The path before copying the file
path = '/home/User/Documents'
print("The path before copying the file:")
print(os.listdir(path))

source = "/home/User/Documents/file.txt"
destination = "/home/User/Desktop"
# Copying the content

dest = shutil.copy(source, destination)
# The path after copying the file
print("The path after copying file:")
print(os.listdir(path))

Output:

The path before copying the file: 
['rashi.png', 'sample.txt', 'file.text', 'copy.cpp']
The path after copying file:
['one.txt', 'demo.txt', 'file.txt', 'demo2.py']

Note: If the destination is a file and if it exists, it will be replaced with the source document, if not another document will be created.

shutil.copy2()

The shutil.copy2() method is similar to the shutil.copy() method with little advanced functions. This method attempts to preserve the document’s metadata. In this method, the content of the source document gets copied to the destination. Along with this, the metadata and other data of a source document additionally get copied.

Syntax: 
shutil.copy2(source, destination)

Here’s a typical example that will showcase the working principle of the shutil.copy2() method:

# importing the os and shutil modules
import os
import shutil

# The path before copying the file
path = '/home/User/Documents'
print("The path before copying the file:")
print(os.listdir(path))
source = "/home/User/Documents/file.txt"

# Copying the metadeta
metadata = os.stat(source)
print("Metadata of source:", metadata)
destination = "/home/User/Desktop"

# Copying the content
dest = shutil.copy2(source, destination)
# The path after copying the file
print("The path after copying file:")
print(os.listdir(path))

# Metadata of destination file
matadata = os.stat(destination)
print("Metadata of destination:", metadata)

Output:

The path before copying the file:
['rashi.png', 'sample.txt', 'file.text', 'copy.cpp']
Metadata of source:
os.stat_result(st_mode=33188, st_ino=801113, st_gid=1000, st_size=84, st_mtime=1558866156, st_ctime=1558866156)
The path after copying the file:
['rashi.png', 'sample.txt', 'file.text', 'file(copy).txt', 'copy.cpp']
Metadata of destination:
os.stat_result(st_mode=33188, st_ino=801111, st_gid=1000, st_size= 84, st_mtime=1558866156, st_ctime=1558933947)

Method 2: Using The os Module

os.popen()

The os.popen() method is used to create a pipe using a command. It returns a file object which interfaces with the pipe. You can utilize it for writing or reading the file, i.e., ‘r’ or ‘w’.

Syntax:
os.popen(command[, mode[, bufsize]])

If the bufsize value is 0, then, at that point, no buffering will happen. If the bufsize value is 1, line buffering will occur. If the bufsize becomes more than 1, buffering will happen with the predetermined buffer size. For a negative value, the system will use the default size.

Example:

# Importing the os module
import os
os.chdir(r'/home/User/Documents/demo.txt ')
# Setting the file of both source and the destination
source = os.getcwd() + "\source"
destination = os.getcwd() + "\destination"
# Copying the contents from source to destination
os.popen('copy source\demo.txt destination\demo.txt')

Note: The os.popen() method was deprecated in Python 2.6. As another option, the Python documentation encourages us to utilize the methods from the subprocess module.

Method 3: Using The subprocess Module

The subprocess module is utilized in Python to execute a new subprocess from our application and associate with the pipes and input-output and get their return codes. 

subprocess.call()

The call() method of the subprocess module can be utilized to execute any command that is passed as an argument. The return value will be the end status of the command that was executed.

Syntax:
subprocess.call(args, stdin = None, stdout = None, stderr = None, shell = False)

Here, the args parameter includes the shell command. 

Note: Python documentation mentions that using shell = True can prove to be a security risk.

Example:

# Importing the subprocess module
import subprocess

# Copying the contents from source to destination
status = subprocess.call('copy file.txt demo.txt', shell=True)

The above example will copy file.txt into the file demo.txt.

Conclusion

In this tutorial, we have covered different ways of copying a file in Python. We hope this has been informative. Please stay tuned and subscribe for more tutorials in the future.

Post Credits: Rashi Agarwal and Shubham Sayon


Recommended: Finxter Computer Science Academy

  • One of the most sought-after skills on Fiverr and Upwork is web scraping. Make no mistake: extracting data programmatically from websites is a critical life skill in today’s world that’s shaped by the web and remote work.
  • So, do you want to master the art of web scraping using Python’s BeautifulSoup?
  • If the answer is yes – this course will take you from beginner to expert in Web Scraping.