Today I (re)learned how to delete a file in Python with the module pathlib.
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
rm to exist,
especially because the method
rmdir is the method that removes directories.
pathlib.Path method to remove a file is
If you have a path
filepath that points to an existing file,
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!
I hope you learned something new! If you did, consider following the footsteps of the readers who bought me a slice of pizza 🍕. Your small contribution helps me produce this content for free and without spamming you with annoying ads.