In this short guide, I’ll show you different techniques for how to copy file in python. So without wasting any further time let’s get started.
1. Copy File In Python By Using Shutil Module
The shutil is the builtin python module that provides functions to perform high-level operations with files.
The copyfile(source, destination) function can be used to copy files from the source path to the destination path. Here is the code.
# program to copy file in python import shutil # Path of the Source file source = "D:\\test.txt" # Destination path destination = "D:\\folder\\new.txt" # Copy file from source to destination shutil.copyfile(source, destination)
The below screenshot shows that the file has copied successfully!
Possible Errors And Handling
Here is the list of important errors that can be thrown while copying a file.
|PermissionError||This error is thrown if os does not give permission to copy.|
|shutil.SameFileError||This error occurs if the source and destination are the same.|
|IsADirectoryError||This error occurs if destination path is a directory.|
Below code shows how we can handle these errors by using try-except block.
import shutil # Path of the Source file source = "D:\\test.txt" # Destination path destination = "D:\\folder\\new.txt" try: shutil.copyfile(source, destination) # If os did n't give permission except PermissionError: print("Permission denied") # If source and destination are same except shutil.SameFileError: print("Source and destination are files") # If the destination is a directory. except IsADirectoryError: print("Destination is a directory.") except: print("Unknown Error.")
2. By Using os module
The os.system function from the os module allows us to execute os commands directly from the python script.
It takes a string command as an argument and returns its exit status from the shell.
Below code shows how to copy file by using os.system()
For Windows OS
# program to copy file in python for windows system import os os.system('copy source.py destination.py')
For Linux Os
import os os.system('cp source.py destination.py')
Also read about How to write a list to a file.