Advertisement
  1. Code
  2. Python

File and Directory Operations Using Python

Scroll to top
Read Time: 5 min

In a previous tutorial, I discussed how we can read, open, close, and write to files. In this tutorial, I will go further and discuss different operations we can perform on files and directories (folders).

For instance, we use files a lot, and working with files goes beyond just opening and closing the file. Do you remember how many times you copied that specific file? Oh, or when you renamed the file you downloaded from some website because it had a meaningless name? Those are some types of operations I'm going to discuss in this tutorial.

Ready? Let's then get to the point and start doing interesting stuff with our files and directories using Python!

shutil

shutil (Shell Utilities) is the name of the module we will be using in this tutorial to carry out different file and directory operations. shutil already comes with your Python installation, so you don't need to manually install it. In order to make use of this module, all you need to do is import the module:

import shutil

Copying Files

Let's start with our first operation, that is, copying files. To do that, we will be using the copy() function from the shutil module. I'm going to use a file titled sample.pdf in this tutorial's examples. You can feel free to use any file you like.

The following simple script will show you how to copy sample.pdf from the desktop (where it is originally located) to another directory Temp, which is also located on the desktop.

Power up the Python interactive shell and type the following commands:

1
import shutil
2
shutil.copy('sample.pdf','Temp')

Notice that I have only listed the file name and the directory name, since I'm working with my Terminal, with the desktop being the path I'm using. You can instead specify the full path to both the file you want to copy and the directory you want to copy the file to, which in my case is as follows:

1
import shutil
2
shutil.copy('/home/vaati/Desktop/sample.pdf','/home/vaati/Desktop/Temp')

Go ahead and open the Temp directory, or any directory you specified, and you should find the copied file there!

What if the second argument was a file instead of a directory? In other words, let's say you typed the following (I removed the full path to the files, assuming they are both on the desktop):

1
import shutil
2
shutil.copy('sample.pdf', 'file.pdf')

In this case, you will have a new file file.pdf, which is a copy of the original file sample.pdf. Thus, if you open file.pdf, you will notice that it has the same content because it is actually a copy of sample.pdf.

Can the source and destination be the same? Let's try and see.

1
import shutil
2
shutil.copy('sample.pdf', 'sample.pdf')

It seems that this operation will bring us an error since the file names shouldn't be the same:

1
Traceback (most recent call last):
2
  File "<stdin>", line 1, in <module>
3
  File "/usr/lib/python3.8/shutil.py", line 418, in copy
4
    copyfile(src, dst, follow_symlinks=follow_symlinks)
5
  File "/usr/lib/python3.8/shutil.py", line 244, in copyfile
6
    raise SameFileError("{!r} and {!r} are the same file".format(src, dst))
7
shutil.SameFileError: 'sample.pdf' and 'sample.pdf' are the same file

Copying Directories

In this section, we are going to see how we can copy a whole directory (folder) rather than a single file, as we saw in the previous section.

Let's say we have the following directory structure which we want to copy. That is, we have a main directory original, which contains a directory original-1, which contains the directory original-2, and which contains the directory original-3, and in original-3 we have our file sample.pdf—phew!

A visualization of what its like to copy directories in PythonA visualization of what its like to copy directories in PythonA visualization of what its like to copy directories in Python

What we want to do now is to copy the directory original with all its contents to a new directory, and call that new directory original-copy.

This can be simply done using the copytree() function, as follows (assuming that everything is happening on the desktop):

1
import shutil
2
shutil.copytree('original','original-copy')

You should now find a new directory original-copy with all the content and structure of original.

Moving Files

Moving a file is like making a cut-and-paste operation on the file. In the Copying Files section, we saw how to make a copy of a file while keeping the original file in its original location.

In this section, we will see how to move (cut) the file to a new location, while removing it at the same time from its original location. This operation is simply carried out using the move() function, as follows:

1
import shutil
2
shutil.move('sample.pdf','temp')

Notice that sample.pdf has been moved to the directory temp and no longer exists on the desktop.

What if we moved sample.pdf to a new file new-sample.pdf, as follows?

1
import shutil
2
shutil.move('sample.pdf','new_sample.pdf')

In this case, you will only have new-sample.pdf with the same content as sample.pdf, but that file no longer exists.

Moving Directories

Moving directories is carried out using the same function we used in the Moving Files section, that is move(). Let's use the same example as in the Copying Directories section, but now with the move() function.

1
import shutil
2
shutil.move('original', 'original-copy')

In this case, you will have a new directory original-copy with the same content as original, but that directory no longer exists.

Renaming Files and Directories

Guess what? You can also use the move() function to rename a file or directory. I will not repeat the examples again in this section. But remember that when applying the move() function on both files and directories above, we mentioned that the original file/directory no longer exists, but a new file/directory with the same content does exist. This is like renaming a file/directory, isn't it?

Deleting Files and Directories

It seems that the shutil module does not contain a function for deleting files. It does, however, contain a function for deleting directories: rmtree(). Be careful because the deletion is permanent, and thus you will not find the deleted directory in your Trash.

The example below shows how we can permanently delete the original-copy directory:

1
import shutil
2
shutil.rmtree('original-copy')

If you want to permanently delete a file, you can use the remove() function from Python's os module, as follows:

1
import os
2
os.remove('sample.pdf')

Conclusion

As you can see, we were able to carry out important operations on files and directories—copy, move, rename, and delete—very easily through the shutil and os modules. You can consult the documentation of these modules for more information on what you can do with them.

Advertisement
Did you find this post useful?
Want a weekly email summary?
Subscribe below and we’ll send you a weekly email summary of all new Code tutorials. Never miss out on learning about the next big thing.
Advertisement
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.