Python shutil

Python shutil module enables us to operate with file objects easily and without diving into file objects a lot. It takes care of low-level semantics like creating file objects, closing the files once they are copied and allows us to focus on the business logic of our program. Let’s see shutil module in action here.

Python shutil example

Let’s look into different examples to understand shutil module.

Copy File

Using shutil’s copyfile() function, it is easy to copy a file to a new file in current directory only.

Here is a sample program on how we can make a new clone of existing file in our current directory:

This function is different from copyfile() function as the later takes a file name as a parameter whereas the copy() function takes directory name as an input.

Finally, the permissions of the file are also cloned when copying a file with both the functions but metadata is not copied, which means that new file created will have a freshly created time instead of the original file’s time.

Copying file with Metadata

If you need to make an exact clone of the file, along with the permissions and the metadata of a file as well, we can make use of the copy2() function. Note that this might not work completely on a POSIX based system.

Here, we print contents of current directory. Before running the script, the journaldev directory exists in current folder. After running the script, it is deleted along with the contents. Let’s see the output for this program:

Remove complete directory tree

Finding files

The which() function presents an excellent tool to find a file on your machine which is present on the PATH.

Conclusion

In this lesson, we studied how we can work with high-level file operations like copying contents of a file, create a new copy of a file etc. without diving into complex File Handling operations with shutil module in Python.

Popular Categories

Newsletter for You

Don't miss out!

Subscribe To Newsletter

We promise not to spam you. Unsubscribe at any time.

Invalid email address

Thanks for subscribing!

JournalDev is one of the most popular websites for Java, Python, Android, and related technical articles. Our tutorials are regularly updated, error-free, and complete. Every month millions of developers like you visit JournalDev to read our tutorials.

JournalDev was founded by Pankaj Kumar in 2010 to share his experience and learnings with the whole world. He loves Open source technologies and writing on JournalDev has become his passion.