Delete a file in Python


Python Delete

In Python, we can use any of the three methods to delete a file or folder that is no longer needed:

  1. os module
  2. pathlib module
  3. shutil module

os module

With the help of the os module, we can check if a file exists in the directory, delete a file and delete a directory. To use the os module, we have to import the os module.

Check if file exists

To check whether the file exists in the directory or not, we have to use os.path.isfile(file path).

When file exists.

In [1]:
import os
file_name = "Test File.txt"
if os.path.isfile(file_name):
    print("File is available.")
else:
    print("File does not exist.")
File is available.

When file does not exists.

In [2]:
import os
file_name = "Test File_2.txt"
if os.path.isfile(file_name):
    print("File is available.")
else:
    print("File does not exist.")
File does not exist.

Deleting a File

To delete the file, we use os.remove(filepath/filename).

In [1]:
import os
file_name = "Test File.txt"
if os.path.isfile(file_name):
    os.remove(file_name)
    print("File deleted successfully.")
else:
    print("File does not exist.")
File deleted successfully.

Delete a Directory

To delete a directory, we use os.rmdir(directory path).

Note:- We can delete only empty directory using os.rmdir.

In [1]:
import os
os.rmdir("Empty Folder")

pathlib module

The pathlib module is available for python version 3.4+.

Delete a File

First we create the Path object and then use the unlink() function.

In [1]:
import pathlib
file = pathlib.Path("Test File.txt")
file.unlink()

Delete a Directory

Again, we have to first create the path object and then use the rmdir() function.

Note: With rmdir(), we can only delete the empty directories.

In [1]:
import pathlib
folder = pathlib.Path("Empty Folder")
folder.rmdir()

shutil module

Delete a File

The shutil cannot be used to delete a file.

Delete a Directory

With the shutil module we can remove a directory using the rmtree() method.

Note: With this, we can remove non-empty directory as well.

In [1]:
import shutil
shutil.rmtree("non-empty folder")