How To Delete A File In Python?

If you are new to Python, you may be wondering how to delete a file. This quick tutorial will show you how to delete a file in Python.

Checkout this video:

Introduction

Deleting files is probably one of the most common file operations you perform on a computer. Although it seems like a simple task, there are actually several different ways to delete a file in Python. In this article, we’ll take a look at some of the most common ways to delete files in Python.

Deleting a Single File

Deleting a single file is pretty easy in Python. We just have to use the os.remove() function. But, before removing a file, you would probably want to check if the file exists or not, so that you don’t end up deleting something else by mistake!

Here’s how we can do that:
“`
import os

# Function to delete
# a single file
def deleteFile(filename):

# Deletes the contents of
# the given filename
with open(filename, “r+”) as f:
f.truncate(0)

os.remove(filename)

Deleting Multiple Files

Deleting multiple files can be done with a for-loop:

for file in os.listdir(“folder”):
if file.endswith(“.txt”):
os.remove(os.path.join(“folder”, file))

Deleting a Folder and its Contents

Deleting a folder and its contents is simple in Python. You just need to use the shutil library.

The shutil library has a function called rmtree that you can use to delete a folder and its contents.

Here is an example of how to use it:

import shutil

shutil.rmtree(“folder_name”)

Deleting a File That is Open

It is not possible to delete a file that is currently open. You must close the file before you can delete it.

Deleting a File That is in Use

It is not possible to delete a file that is in use. You must first close the file before you can delete it.

Deleting a File That is Read-Only

Deleting a read-only file may cause an error on Windows. If you open the file’s Properties window, you can see if the read-only check box is selected or not. If it is, clear the check box, and then try to delete the file again.

Deleting a File That is Hidden

If you want to delete a hidden file, you need to pass the -i option along with the rm command. Use the following syntax:

rm -i filename.txt

If you want to delete a symbolic link, you can use the os.remove() or os.unlink() methods. If the symbolic link points to a directory, then you can use the shutil.rmtree() method.

Conclusion

Now that you know how to delete a file in Python, you can easily get rid of any unwanted files on your computer. Just remember to use the delete() method and specify the path to the file that you want to delete.

Scroll to Top