Copy files using python

This article is about copying the contents of one file to another using python. This is possible with the help of a built-in python library called shutil. This library just copies the contents of the source file to the destination file in a single line of code.

How does it work?

The shutil module has a method called copyfile(). This method takes the source file name and the destination file name as the parameters. The copy of the source file is made in the same directory as the program unless a complete path is given as the destination file name.

code

import shutil

shutil.copyfile('sample.txt', 'sample1.txt')

Note: Make sure the sample.txt is in the same directory as the python program. If not, give the absolute path as the file name.

example: home/projects/sample.txt

This will copy the contents of the source file to the destination file.

Exceptions

The following two type of exceptions are commonly encountered with this method. They are,

  1. FileNotFoundError
  2. SameFileError

1. FileNotFoundError

As the name suggests this error is raised when the source file does not exist. If this error occurs even if the source file exists, then try giving the absolute path instead of just giving the filename.

import shutil

shutil.copyfile('my_file.txt', 'copy.txt')

Since my_file.txt does not exist in my current directory I get the following error from the debugger.

file not found error

If your python code and the file exists in different directory, give the filename as absolute path like this.

import shutil

shutil.copyfile('home/text_files/my_file.txt', 'copy.txt')

2. SameFileError

The next common type of exception is the SameFileError. This will occur if the source file and the destination files have the same name.

import shutil

shutil.copyfile('hello.txt', 'hello.txt')

The above code will generate the following error on the console.

same file error

4 thoughts on “Copy files using python

Leave a Reply

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