Python Delete File Function With Examples

Python Functions to Delete Files and Folders

The table shown below shows the Python functions to delete files and directories.

Python Functions To Delete Files and FoldersDescriptions
os.remove(‘file_path’)Removes the specified file.
os.unlink(‘file_path’)Removes the specified file. Useful in UNIX environment.
pathlib.Path(‘file_path’).unlink()Delete the file or symbolic link in the mentioned path.
os.rmdir(’empty_dir_path’)Removes the empty folder.
pathlib.Path(’empty_dir_path’).rmdir()Unlink and delete the empty folder.
shutil.rmtree(‘dir_path’)Delete a directory and the files contained in it.

How to Delete File in Python?

The os.remove() method deletes single Python files.

However, os.rmdir() removes a file or a directory, while the shutil.rmtree() method will delete a directory and the files contained in it.

  • os – This module provides functions for interacting with the operating system. OS module comes under Python standard utility modules. This module provides a portable way of using operating system-dependent functionality.

    All functions of the OS module raise OSError in case of invalid or inaccessible file names and paths or other arguments that have the correct type but are not accepted by the operating system.
  • shutil – Shutil module provides many functions for high-level operations on files and collections of files. It comes under Python standard utility modules. This module helps automate the process of copying and removing files and directories.

    shutil.rmtree() is used to delete an entire directory tree; the path must point to a directory.
  • pathlib – The pathlib module offers classes representing filesystem paths with semantics appropriate for different operating systems. Thus, when we need to work with files in multiple environments, we can use the pathlib module.
Deleting a single file?OS
Pathlib
os.remove()
path_object.unlink()
Deleting empty directories?OS
Pathlib
rmdir()
Deleting non-empty directories?Shutilrmtree()

Method 1. Using the OS Module in Python

The os module allows users to use operating system-depend functionalities.

Before we use the os module to delete a file, we need it to import first, then use the remove() function provided by the module to delete the file. It takes the file path as a parameter.

Here’s the syntax to delete a file in Python using the os module:

import os
file_path = <file_path>
if os.path.isfile(file_path):
  os.remove(file_path)
  print("File has been deleted")
else:
  print("File does not exist")

In the code given above, we first import the os module and then store the file path of the file you want to delete in a variable named file_path.

After that, we put the condition that if the file exists at the path, then remove the file; otherwise, the file does not exist.

On the other hand, if you want to delete or clear a directory, you can do this with the help of the rmdir() function of the os module.

*Note that the directory must be empty for this to work.

import os

  os.rmdir('directory')

Method 2. Using the Shutil Module in Python

The shutil module is a high-level file operation module. You can perform functions like copying and removing files and collections of files.

Also, this module can be used as the os module to delete files or directories. But here, the directory does not need to be empty.

If you want to delete a directory using shutil, you can also delete all the contents inside files and sub-directories.

The function of the shutil module is rmtree().

import shutil

  shutil.rmtree('path')

Now here is the place of the path. You can provide the path to your directory that you want to remove.

You can’t delete a single file with the shutil.rmtree() function.

Method 3. Using the Pathlib Module in Python

If you’re working with Python version 3.4 and above, then the pathlib module is beneficial for deleting or removing files.

This pathlib module has many similarities with the os module, two of them being the remove and rmdir methods.

Now, to work out this module properly, you must first create a path object.

When an instance of the path class is created, a windowspath or posixpath will be returned according to the machine you’re working on.

For Windows OS, a windowspath object will be returned. And for non-Windows OSes like Linux, a posixpath will be returned.

import pathlib
p_object = Path(".")
type(p_object)

Then, the next step is to use the unlink() function.

The unlink() function is used to remove the file or the symbolic link.

If you want to delete a directory, you must use the rmdir() function instead.

import pathlib
file = pathlib.Path("test/file.txt")
file.unlink()

In the same way, if you want to delete a directory:

import pathlib
directory = pathlib.Path("files/")
directory.rmdir()

But the rmdir() function only allows you to delete empty directories.

Also read: Python Print Dictionary (With Examples)

Conclusion

In this article, we have completely discussed Delete File with Python and its different functions, and with the help of the given examples, we learned it quickly and easily.

I hope this simple tutorial helped you a lot to comply with your requirements.

If you have any questions or suggestions about this tutorial for Delete a File Python, please feel free to comment below.

Leave a Comment