Checking Whether a File Path Exists
In this lesson, you will learn how to check whether a file path exists or doesn’t exist. To start this off, it might be unintuitive, but you can create
Path objects whether or not the file path exists.
It just probably doesn’t make much sense to do so unless you’re planning to create it later on. And you can do this check by using the
.exists() method on a
Path object, which returns
True if the path exists and else
So if you’ve been paying close attention in the previous videos, you’ve seen that I referenced a file called
"hello.txt" a couple of times. The first time was when we were reading in the content of this file, and that file was located in the documents folder.
And then later on, I was talking about the desktop and the file
hello.txt there. And now we’ll use this to see which of those two files actually exists. Again, I will need to create the path for both of these.
And then I’ll make another one that I call
hi_docs. And that’s the documents folder followed again by the name of the file. Okay, so this is just a little bit more training of how do you combine paths and build
Path objects you just learned before, and now you have this path that points to
/Users/martin/Desktop.hello.txt and then the docs path that points to a file called
hello.txt in the documents folder.
So this tells me that on this path,
Documents/hello.txt, there is actually a file—it’s called
hello.txt—and in the other path that goes across my desktop, there is no file called
Now there’s more that you can do, somewhat related operations. You can figure out whether a path points to a file or to a folder and you can do that by saying
hi_—well, just in this case you use the method that is called
.is_dir(). Start off by using
Phew, my desktop is still there. That’s good to know. Now is it a directory?
desk.is_dir() and that also returns
True. So these three methods can be useful to figure out does a file or a directory exist, and what is it? Is it a file or a directory?
So as you’ve seen, you can create
Path objects whether or not the file path exists. You’ve seen that with the
hello.txt file on the desktop that doesn’t actually exist, but we still had a
Path object that points to that location.
I’ll leave you with this slide. Those are three useful methods that we can use on
Path objects and to get about an idea of what is there on your file system. Is it a file, is it a folder, is it there at all, basically?
Become a Member to join the conversation.