Skip to Content

3 Ways to Delete a File in Python

There are a few different ways to delete a file in Python. In this blog post, we will discuss the 3 best methods for deleting a file. Each method has its own benefits and drawbacks, so it is important to choose the right method for your specific needs. Let’s get started!

The following ways can be used to delete files in Python

  • import os; os.remove(“test.txt”)
  • import shutil; shutil.rmtree(“test.txt”, ignore_errors=False, onerror=None)
  • import os; os.system(‘rm test.txt’)

 

Delete a File with the os.remove function in Python

The best way to delete a file in Python is to use the built-in remove function in os module . The remove() function will delete a given filename from your filesystem. Simply type “os .remove(filename)” at the command line, and Python will delete the file.

Get Your Free Linux training!

Join our free Linux training and discover the power of open-source technology. Enhance your skills and boost your career! Learn Linux for Free!

This method takes a single argument which should be a string representing the path of the file you want to delete.

The os.remove() function has a few benefits. However, there is one major drawback to using this method: it cannot be used on directories (folders). If you try to remove a directory with the remove() function, Python will instead throw an error message.

If the specified file doesn’t exist a FileNotFoundError error is thrown. If the given path points to a directory, they will trow IsADirectoryError error.

Deleting a file requires a write and execute permission on the directory containing the file. Otherwise, you will get PermissionError error.

Example 1 of Deleting a File with the os.remove function

import os
os.remove(“test_file.txt”)
print(“File removed successfully”)

Example 2 of Deleting a File with the os.remove function

import os
#checking if file exist or not
if(os.path.isfile(“test.txt”)):
#os.remove() function to remove the file
os.remove(“test.txt”)
#Printing the confirmation message of deletion
print(“File Deleted successfully”)
else:
print(“File does not exist”)
#Showing the message instead of throwing an error

Example 3 of Deleting a File with the os.remove function

import os
from os import listdir
my_path = ‘C:\Python Pool\Test\’
for file_name in listdir(my_path):
if file_name.endswith(‘.txt’):
os.remove(my_path + file_name)

Delete a entire directory and all of its contents with the shutil.rmtree

The second method for deleting a directory is to use the shutil.rmtree command. This function will delete an entire directory and all of its contents, including subdirectories and files. Simply type “shutil . rmtree(directory)” at the command line, and Python will delete the directory.

shutil.rmtree(path, ignore_errors=False, onerror=None)

shutil.rmtree() – by passing ignore_errors=True in shultil.rmtree() we can ignore the errors encountered. It will go forward with deleting all the files and skip the files which raise exceptions while deleting.

Example of using shutil.rmtree function to delete a entire directory and all of its contents

import shutil
import os
# location
location = “E:/Projects/PythonPool/”
# directory
dir = “Test”
# path
path = os.path.join(location, dir)
# removing directory
shutil.rmtree(path)

Delete a File with OS module system method

The OS module in Python provides functions for interacting with the operating system. OS, comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality. os.system() method executes the command (a string) in a subshell. we can also use this method to delete files.

Example of using os module to delete a file

import os
os.system(‘rm test.txt’)