How to Delete Files in Python [5 Ways]

Do you want to delete the existing files in Python? In this Python tutorial, I will explain “How to Delete Files in Python if it exists” using 4 different methods with some practical examples. Also, I will explain how to delete multiple files at once.

To delete existing files in Python, we can use some built-in methods like the os.remove() method, os.unlink(), file_path.unlink(), os.system(), and subprocess.run([]). Also, we will use os.walk() to create a list of existing files in the directory to delete all the files simultaneously.

Delete Files in Python

Here is the list of all the methods that can be used to delete an existing file in Python:

  • os.remove()
  • os.unlink()
  • Path(“file_path”).unlink()
  • os.system()
  • subprocess.run()

I will also explain how to delete multiple files in Python.

How to Delete Files in Python using os.remove()

The os.remove() function is part of the os module in Python, which is used to delete files from the directory specified by its path if the file exists.

If the file does not exist, it will raise a “FileNotFoundError” error in Python.

Here is an example of deleting a file in Python using the os.remove() function in Python:

 import os

try:
    file_path = r" # Please add your file path here "
    os.remove(file_path)
    print("File has been deleted successfully")
except FileNotFoundError:
    print("File not found")
except PermissionError:
    print("You don't have permission to delete this file")

Here is a screenshot after we ran the code in the Python editor:

python delete files in directory

How to Delete Multiple Files in Python

You can also delete multiple files in Python using the built-in functionalities of the os module.

We will use os.walk() to create a Pyhton list of the existing files in a directory and then os.remove() to remove a file in Python.

import os

def get_all_files_in_directory(directory_path):
    file_paths = []
    for root, _, files in os.walk(directory_path):
        for file in files:
            file_paths.append(os.path.join(root, file))
    return file_paths

directory_path = r'C:\Users\Asus\OneDrive\Desktop\Articles\Core Python\5 different ways to Delete files in Python'
all_files = get_all_files_in_directory(directory_path)

for file_path in all_files:
    if ".txt" in file_path:
        os.remove(file_path)

Note: In this program, I’ve only given a condition to remove text files(.txt).

remove multiple files from folder in python

Use os.unlink() to remove files in Python

I’ve used the unlink() method to delete files from the directory in Python. It is an in-built method of os library that removes files in Python.

Here is an example:

import os

file_path = r'C:\Users\Asus\OneDrive\Desktop\Articles\Core Python\5 different ways to Delete files in Python\file4.txt'
os.unlink(file_path)
erase file from directory in python

Delete all files from the folder in Python using the unlink method.

To delete all the files from the directory in Python, you can use the unlink() method of os library.

Here is the code to delete all files from the folder if they already exist in Python.

import os

def get_all_files_in_directory(directory_path):
    file_paths = []
    for root, _, files in os.walk(directory_path):
        for file in files:
            file_paths.append(os.path.join(root, file))
    return file_paths

directory_path = r'C:\Users\Asus\OneDrive\Desktop\Articles\Core Python\Contian_files'
all_files = get_all_files_in_directory(directory_path)

count = 0
for file_path in all_files:
        os.unlink(file_path)
        count += 1
        
print(f"Total {count} files has been deleted successfully")

Here is the screenshot of the output of the code:

How do you delete a file if already exists in Python

Remove the File from a folder using pathlib.Path.unlink()

We can erase the file in Python using the unlink() method of the pathlib module in Python.
Here is an example of deleting a file in Python using the pathlib.

from pathlib import Path
try:
    file_path = Path(r"C:\Users\Asus\OneDrive\Desktop\Articles\Core Python\Contian_files\file2.txt")
    file_path.unlink()
    print("File Removed Successfully")

except Exception as e:
    print(f"Something went wrong: {e}")

Note: If you want to remove multiple files using this method, you can use a for loop in Python. You can take reference from our previous example in this article.

delete all files in python

Delete a file in Python by using os.system()

By using the os.system() method of Python, we can perform so many tasks including removing a file in Python. You will use shell commands as a parameter of this method.

Here is an example of deleting a file using Python:

Code For Windows OS:

import os

file_path = r'C:\Users\Asus\OneDrive\Desktop\Articles\"Core Python"\5_different_ways_to_Delete_files_in_Python\file3.txt'

os.system(f"del {file_path} ") # For windows, we will use "del"

Code For Linux or Mac :

import os

file_path = r'C:\Users\Asus\OneDrive\Desktop\Articles\"Core Python"\5_different_ways_to_Delete_files_in_Python\file3.txt'

os.system(f"rm {file_path} ")
 # for mac and linux, we will use "rm"

Python Delete File using the run method

We will use the run method of the subprocess module in Python. We will give shell commands as a parameter to remove the file using Python.

Let’s take one example to remove a file in Python.

import subprocess

file_path = r'C:\Users\Asus\OneDrive\Desktop\Articles\Core_Python\5_different_ways_to_Delete_files_in_Python\demo.txt'

subprocess.run(['cmd', '/c', 'del', file_path])

Conclusion

In this Python article, we’ve explained multiple ways to remove files using Python. We gave examples for using the os.remove() method, os.unlink() method, using pathlib.Path.unlink(), then os.system(), and subprocess.run() to remove the file. We’ve also explained how to remove multiple files using a loop in Python.

You may also like to read: