Each file or folder in the filesystem has a path, a specific one. Python coders deal a lot with paths of files in their computer programming projects, especially when developing software that deals with the utilities of the operating system. Being rich in already builtin features, Python offers many utilities that can help the coder accomplish the tasks they want, without any pain.
One can easily use the os module offered by Python to check if a specific path exists on their operating system or not. The following syntax, shows the usage of the os.path.exists utility.
When the os.path.exists Python statement is executed, it returns True or False, depending on the existence of the path which is being checked. It’s usage is very easy, but before one can do that, they have to import the os module first, like shown below.
Once the Python os module is imported, one can easily utilize its resources. Since the purpose of this tutorial is to teach one how to check for the existence of the path of a file in their operating system, I am giving the following practical example to illustrate it.
When the above statements are executed in the interactive Python shell, False is being returned.
Why? Because the path which we are looking for does not exist in the system. With the main purpose of illustrating the usage of the os.path.exists utility when a path exists, I am running the example shown below on my unix based machine.
When the above Python statement is executed on the Python interactive shell, on my computer, the True value is being returned.
This time the True value is being returned, because the path which I am checking for, exists in the operating system.
Python comes with the builtin tools that can help the coder solve almost any kind of problem. By using the os.path.exists utility, one can check for the existence of a path in their operating system.