Python shutil copy file + Examples

In this Python tutorial, we will understand how to use the shutil.copy() method in Python to copy a file content.

Recently, when I was working with files using Python, I came to know about shutil module in Python. This module allows performing high-level operations on files or collections of files.

However, in this tutorial, we will focus on copying the content of a file using the shutil module. Here is the set of topics that we will cover.

  • How to copy file using shutil.copy() in Python
  • How to copy file to directory using shutil.copy() in Python
  • How to copy file if exists using using shutil.copy() in Python
  • Solve python shutil copy file not found error
  • How to copy file and create directory using shutil.copy() in Python
  • How to copy file from one directory to another using shutil.copy() in Python
  • How to copy file and preserve timestamps using shutil.copy() in Python

Python shutil copy file

In Python, the shutil is a built-in module that offers multiple methods to perform high-level operations on files. Moreover, this module consists of multiple methods that we can utilize to copy files in Python.

One such popular method in shutil module is the copy() method. The copy() method in shutil module can copy a file from a source file to another file or to a specified directory.

However, this method copies only the data and file permission mode. But it does not hold any metadata related to a file, for example, file creation time, file modification time, etc.

Note: if you want to copy a file in Python with its metadata, you can use copy2().

Here is the syntax of using the stutil.copy() method in Python.

shutil.copy(src_file, [dst_file or dst_directory], *, follow_symlinks=True)

The syntax consists of the following elements.

ParameterDetail
src_fileThis parameter is utilized to specify the path of the source file
dst_file or dst_directoryThis parameter is utilized to specify either the destination file or destination directory
follow_symlinksIf it is False src_file will be the symbolic link and a symbolic link will be constructed for the destination. However, its default value is True.

Next, we will look at an example of how to use the Python shutil.copy() method to copy files. Here is an example.

# importing modules
import shutil
import os

# path of the src directory
path = r'D:\test-1'

# Listing all files from src directory
print("List of files in source directory:")
print(os.listdir(path))
 
# Path of src file
src_file = r"D:\test-1\USA_Cities_Data.csv"
 
# Path of dst file
dst_file = r"D:\test-2\USA_Cities_Data(copy).csv"
 
# Copying file from src to dst
dest = shutil.copy(src_file, dst_file)

 
# Printing path of new file in destination
print("Destination path:", dest)

In the above example, we are copying the data of the USA_Cities_Data.csv file from the test-1 directory to the USA_Cities_Data(copy).csv file in the test-2 directory.

READ:  Python select from a list + Examples

However, if the USA_Cities_Data(copy).csv file does not exist in the designation, it will create the file with the same specified name and copy data.

Python shutil copy file
Copying file from test-1 to test-2 directory using python

So, in this section, we have covered how to copy file data from one file to another using shutil.copy() in Python.

Read: Get current directory Python

Python shutil copy file to directory

Here we will understand the use of shutil.copy() method to copy files to a destination directory.

As discussed in the above section, while using the copy() method, we can either specify the file or a directory name in the destination parameter.

So, here we will see an example of how to copy files to a directory using shutil.copy() method in Python.

Here is the code for the example in Python.

# importing modules
import shutil
import os

# path of the src directory
path = r'D:\test-2'

# Listing all files from dst directory
print("List of files in destination directory before copy:")
print(os.listdir(path))
 
# Path of src file
src_file = r"D:\test-1\USA_Cities_Data.csv"
 
# Path of dst file
dst_file = r"D:\test-2"
 
# Copying file from src to dst
dest = shutil.copy(src_file, dst_file)

print("File copied successfully") 

# Printing path of new file in destination
print("Destination path:", dest)

print("List of files in destination directory after copy:")
print(os.listdir(path))

In the example, we are copying the USA_Cities_Data.csv file from the test-1 directory to the test-2 directory in Python.

Python shutil copy file to directory
Copying files to a directory in Python

In this section, we have seen how to python shutil copy files to a directory using an example.

Read: PdfFileMerger Python examples

Python shutil copy file from one directory to another

In this section, we will understand how to copy files from one directory to another using shutil.copy() method.

And for this task in Python, you can consider the following sample code.

# importing modules
import os
import shutil

# path of the src & dst directory
src_directory = r"D:\test-1\\"
dst_directory = r"D:\test-2\\"

# fetching all files from src directory
for file in os.listdir(src_directory):
    # Defining full file path
    source = src_directory + file
    destination = dst_directory + file
    # copying files
    if os.path.isfile(source):
        shutil.copy(source, destination)
        print("file:", file, "copied")

In this example, we are copying all the files which are there in the test-1 directory to the test-2 directory using the shutil.copy().

  • Here, first, we define the path for the directories.
  • Then we iterated over each file given in the source directory (test-1).
  • In last, we copied all the files from the test-1 (src) to the test-2 (dst) directory.
Python shutil copy file from one directory to another
Copying files from one directory to another using Python

So, in this section, we have understood how to python shutil copy files from one directory to another using stutil.copy().

Read: Python read a file line by line

Python shutil copy file and create directory

In this section, we will focus on how to first create a new directory using Python and then copy a file into the new directory using shutil.copy().

So, first, to make a new directory using Python, we will use the os module. The os module in Python consists of the mkdir() method which is equivalent to using mkdir command in your Windows command prompt.

READ:  Write a Python program to print the number of elements present in an array

However, once the directory is created, we can use copy() method from shutil module to copy files into it.

Here is a sample example of this execution in Python.

# importing modules
import shutil
import os

# Path of src file
src_file = r"D:\test-1\USA_Cities_Data.csv"
 
# Path of dst file
dst_directory = r"D:\test-3"

# Creating new directory
os.mkdir(dst_directory)
print("New Directory Created Successfully")
 
# Copying file from src to new directory
dest = shutil.copy(src_file, dst_directory)

print("File copied successfully") 

# Printing path of new file in destination
print("Destination path:", dst_directory)

print("List of files in new directory after copying:")
print(os.listdir(dst_directory))

In the above example:

  • First, we have defined the path for the source file which is USA_Cities_Data.csv.
  • Then we used the os.mkdir() method to create a new test-3 directory.
  • In the last, we used the shutil.copy() method to copy the USA_Cities_Data.csv file to test-3 directory.
Python shutil copy file and create directory
Creating a directory and copying files into it using Python

So, in this section, we understood how to create and copy files into a new directory using Python.

Read: Python write a list to CSV

Python shutil copy file not found

Till now, in this Python tutorial, we have seen how to copy files using Python when we specify the correct file name. However, there could be chances where we specify the wrong file name.

In such cases, the shutil.copy() will return:

FileNotFoundError: [Errno 2] No such file or directory

Here is the sample example where shutil.copy() method is unable to find the USA_Cities_File.csv file.

Python shutil copy file not found
Python shutil copy file not found

However, to handle this error in Python, we can either use a try-except block to handle this exception. Moreover, we can also try to check the existence of a file before copying its content.

Read: How to write Python array to CSV

Python shutil copy file exists

As discussed earlier, to overcome the FileNotFoundError exception, we can first check the existence of a file in Python. And for this task, we can use various methods from the os module.

  • os.path.isfile(): This method is used to check the existence of a given file path. If the given file path exists, it will return True else False.
  • os.path.isdir(): This method is used to check the existence of a given directory path. If the given directory path exists, it will return True else False.

Now, let us look at an example in Python that uses these methods.

# importing modules
import shutil
import os

# Path of src file
src_file = r"D:\test-1\USA_Cities_Data.csv"
 
# Path of dst file
dst_file = r"D:\test-2"

if os.path.isfile(src_file):
    if os.path.isdir(dst_file):
        try:
            shutil.copy(src_file, dst_file) 
            print("File copies successfully")
        except shutil.Error as e:
            print(e)
    else:
        print("Destination directory does not exist")
else:
    print("Source file does not exits")
  • In this example, we are using the os.path.isfile() and os.path.isdir() methods to check the existence of the source file and destination directory respectively.
  • After this, we were using the shutil.copy() method to copy the source file to the destination directory.
  • Moreover, we also utilized the try-except block to handle exceptions thrown by the shutil module.
Python shutil copy file exists
Copying a file to another folder in Python based on the existence

So, here we have covered how to create a python program for the implementation of Python shutil copy files based on their existence.

READ:  Write a Program to Check Whether a Number is Prime or not in Python

Read: Python write variable to file

Python shutil copy file preserve timestamp

Before we jump to the use of copy() method to preserve timestamps, we need to understand how to fetch the metadata of a file using Python. For this, we use the os.stats() method.

This method returns an os.stat_result object containing metadata for a specified file passed as an argument to the method. Let us understand this concept using an example in Python.

# Importing the os module
import os

# Path of the file
src_file = r"D:\test-1\USA_Cities_Data.csv"

# Printing metadata of the file
metadata = os.stat(src_file)
print("Metadata:", metadata)

In the above example, we are checking the metadata for the USA_Cities_Data.csv file. This program will return the following metadata for the file.

get metadata of file in Python
Fetching metadata of file in Python

Now, if we focus on the metadata, we need to observe the following 3 values.

  • st_atime: It indicates the most recent access time in seconds.
  • st_mtime: This time stamp shows when the content was last modified in seconds.
  • st_ctime: It denotes the time of the most recent metadata modification in seconds.

Now, if use the shutil.copy() method, it will not preserve the timings of the file from the source to the destination.

Python shutil copy file preserve timestamp
Copy() does not preserve time from source to destination file

To preserve the time for the destination file, we need to use copy2() instead of copy() in Python. Here is an example of using the copy2() method which preserves the timestamp for the destination file.

# importing modules
import shutil
import os

# path of the src directory
path = r'D:\test-1'
 
# Path of src file
src_file = r"D:\test-1\USA_Cities_Data.csv"
 
# Printing metadata of src file
metadata = os.stat(src_file)
print("Metadata of src file:", metadata)
    
# Path of dst file
dst_file = r"D:\test-2\USA_Cities_Data(copy).csv"
 
# Copying file from src to dst
dest = shutil.copy2(src_file, dst_file)
print('File copied successfully')

# Printing metadata of src file
metadata = os.stat(dest)
print("Metadata of dst file:", metadata)

In the above example, we utilized the shutil.copy2() method to copy the content of USA_Cities_Data.csv file to USA_Cities_Data(copy).csv. However, when we use the copy2() method, the value of st_mtime is preserved.

Here is the result of the above Python program.

Python shutil copy file preserve timestamp example
Copying file using Python while preserving the timestamp

So, in this section, we understood how to python shutil copy files while preserving the timestamp.

You may also like to read the following Python tutorials.

Conclusion

At the end of this Python tutorial, we have seen various examples of how to copy files using shutil.copy() method in Python. Moreover, we have also discussed the following topics with examples.

  • How to copy file using shutil.copy() in Python
  • How to copy file to directory using shutil.copy() in Python
  • How to copy file if exists using using shutil.copy() in Python
  • Solve python shutil copy file not found error
  • How to copy file and create directory using shutil.copy() in Python
  • How to copy file from one directory to another using shutil.copy() in Python
  • How to copy file and preserve timestamp using shutil.copy() in Python