Deleting a File
So you have this
march.md file in there. It’s got a different ending than the other ones. You’re using a Markdown file here, and maybe planning up ahead until March is maybe just a little bit too far.
Again, you will need the file path to the resource that you want to delete. So I’ll call this
file_path, and it lives inside of the
"monthly". And then you also need the filename, which was
"march.md". Reveal the file path, and let’s double check that I typed the right one by seeing whether it exists.
then you will get a
FileNotFoundError. So I can’t delete this file because there is no file at the end of this path. Now, if you want to avoid raising this
FileNotFoundError, then you can pass an argument to
.unlink() which is called
file_path.unlink() and then you can say
missing_ok. You can already see it’s pointed out here. If I set this to
True instead of the default, which is
FileNotFoundError won’t get raised. And in this case, nothing happens, because the resource at the file path was already deleted before.
So in order to delete a file, you can call the
.unlink() method on a
Path object. And to do that, you first have to define the file path that points to the resource that you want to delete and then call
.unlink() on it.
And here’s an example of that, so you also tried to call
.unlink() on a non-existing file path, and you got a
FileNotFoundError. If you want to avoid raising this error, then you can pass
missing_ok=True when you call
.unlink() on a file path, and then it avoids raising the error if the resource at the end of the path doesn’t exist. And if it exists, then it’s going to delete it.
Become a Member to join the conversation.