Today I (re)learned how to delete a file in Python with the module pathlib.
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
!
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!
+35 chapters. +400 pages. Hundreds of examples. Over 30,000 readers!
My book โPydon'tsโ teaches you how to write elegant, expressive, and Pythonic code, to help you become a better developer. >>> Download it here ๐๐.