Delete a file in Python - Let's use "unlink" function in pathlib

You can easily delete a file using pathlib.

from pathlib import Path

p = Path(__file__).parent / 'data' / 'mail.txt'

p.unlink()

First, get the path of a file you want to delete. Second, use unlink function. After running the code, the file is removed.

If the file doesn't exist, Python raises the FileNotFoundError exception.

FileNotFoundError: [Errno 2] No such file or directory: '/Users/serif/python/test/data/mail.txt'

From Python 3.8, missing_ok option was added. If missing_ok is True, the FileNotFoundError exception is raised when the file doesn't exist.

from pathlib import Path

p = Path(__file__).parent / 'data' / 'mail.txt'

p.unlink(missing_ok=True)

The default of missing_ok is False.

Python File

Python Tutorial