How to Check If a File Exists in a Folder in Python

Python, as a dynamic object-oriented programming language, offers a lot of flexibility and functionalities to its users.

One of these functionalities is accessing files and folders. In this tutorial, we are going to learn How to Check If a File Exists in a Folder in Python. This can be especially handy in situations where your program needs to interact with the filesystem.

Before We Get Started

Before diving into the code, you need to make sure that you have Python installed on your machine. If you don’t have it installed, you can download it from Python’s official website.

Step 1: Access the Filesystem using the os module

Python has a built-in module known as os that allows us to interact with the operating system including the file system. We will use the os module to check if a file exists in a folder.
Here is an example:

Here, we use os.path.isfile() method to check if the file exists. The method returns True if the file exists and False otherwise.

Step 2: Use the Try and Except Block

Another way of checking if a file exists in Python is by using the try and except block. Here is how to do it:

Here, we try to open the file. If the file can be opened successfully, it means that the file exists. If an exception, specifically the FileNotFoundError is raised, it means that the file does not exist.

Final Code

Here is the complete code for the tutorial. In this code, we have wrapped the file-checking logic inside a function named file_exists.

With this code, you will be able to check if a file exists in a directory or not. Feel free to use and adapt this code according to your needs.

Conclusion

Checking if a file exists in a folder is a common need when writing code that interacts with the file system. Thankfully, Python makes it easy to perform this check with in-built functions.

Remember, file handling is a powerful feature in Python and can be used in a number of different projects. Happy coding!