A colourful background with the word β€œunlink” big and centre

Module pathlib

The module pathlib is one of the modules I use the most, but I keep forgetting how to delete files with it. I always expect a method remove, rmfile, or rm to exist, especially because the method rmdir is the method that removes directories.

Alas, the pathlib.Path method to remove a file is unlink!

How to delete a file using pathlib?

If you have a path filepath that points to an existing file, then pathlib.Path(filepath).unlink() will remove that file:

>>> from pathlib import Path
>>> filepath = Path("myfile.txt")  # File I want to delete.

>>> filepath.exists(), filepath.is_file()  # The file exists for now...
(True, True)

>>> filepath.unlink()  # Delete the file πŸ’£

>>> filepath.exists(), filepath.is_file()  # The file no longer exists.
(False, False)

That's it for now! Stay tuned and I'll see you around!

Improve your Python 🐍 fluency and algorithm knowledge 🎯

Get ready for 12 intense days of problem-solving. The β€œAlgorithm Mastery Bootcamp” starts December 1st and it will feature 24 programming challenges, live analysis sessions, a supportive community of like-minded problem-solvers, and more! Join now and become the Python expert others can rely on.

Previous Post Next Post

Blog Comments powered by Disqus.