How to check if a file exists with Python? (without using try)
In this article we will learn how to check if a file exists with Python, with alternative ways, not using the try statement.
Hey you programmer, Is everything OK? Let’s learn more about Python!
In the Python language one of the most used ways to check if a file is present in a directory is with try, let’s see it:
try: f = open('file.txt') f.close() except: print('The file does not exist!')
But there are other ways to check file
We can use the os library, see an example:
import os.path if(os.path.isfile('file.txt')): print("The file exists") else: print("The file does not exist!")
With the isfile method, we can check if the file we want to open is really a file
If we just want to check if the file is in the folder, we have this way:
import os.path if(os.path.exists('/path/to/file.txt')): print("The file exists") else: print("The file does not exist!")
The exists method checks for the existence of the file
As of Python version 3.4 we also have pathlib, which is an object-oriented way to check if the file exists
Let’s see an example:
from pathlib import Path file = Path("/path/to/file.txt") if file.is_file(): print("The file exists") else: print("The file does not exist!")
With this same library it is also possible to check the existence of directories, take a look:
dir = Path("test") if dir.is_dir(): print("the directory exists!") else: print("the directory doesn't exist!")
And these are the ways to check whether or not the file is in our project with Python! 🙂
In this article we learned how to check if a file exists with Python
We use the os library and its methods and also the pathlib, which was added in Python version 3.4
However, it is better to always use try, because the file may be being edited or moved when you use this command.
And try will make sure you don’t run your program wrong
Do you want to learn more about Python? Click here!