Deleting files in Python

Deleting Files in Python

Deleting files is a common operation. Python provides a variety of methods for deleting files. Let’s learn how.

os.remove() Method

Python’s os module provides an interface for manipulating the file system, including os.remove(), which can be used to delete a specified file. Let’s take a look at a simple example:

import os

# Delete the test.txt file
os.remove("test.txt")

pathlib.Path.unlink() Method

Python 3.4 introduced the pathlib module, which provides an advanced path manipulation interface. Use the pathlib.Path.unlink() method to delete a specified file. The following example code is available:

from pathlib import Path

# Delete the test.txt file
Path("test.txt").unlink()

send2trash Library

If we accidentally delete a file and want to restore it, we need to perform some additional steps. Instead of directly deleting the file, we can use the send2trash library. The send2trash library moves the file to the Recycle Bin, making it easy to restore. Let’s look at an example code:

import send2trash

# Move the test.txt file to the Recycle Bin
send2trash.send2trash(“test.txt”)

The try except mechanism

When deleting files, we need to be aware of some exceptions, such as when the file does not exist. To ensure the normal operation of the program, we can use the try except mechanism to catch exceptions. The example code is as follows:

import os

try:
os.remove(“test.txt”)
except FileNotFoundError:
print(“File does not exist”)

Deleting a folder

In actual development, we also need to delete folders. The Python os module provides the shutil.rmtree() method to delete a non-empty folder. The example code is as follows:

import shutil

# Delete the example folder and all its files and subfolders.
shutil.rmtree("example")

Conclusion

So far, we have learned various methods for deleting files. In actual development, we need to choose the method that best suits our specific use case. When deleting files, be careful to handle exceptions to ensure proper program operation.

Leave a Reply

Your email address will not be published. Required fields are marked *