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:
1 2 3 4 5 6 |
import os if os.path.isfile('./example.txt'): print('File exists') else: print('File does not exist') |
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:
1 2 3 4 5 |
try: with open('./example.txt') as file: print('File exists') except FileNotFoundError: print('File does not exist') |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
import os def file_exists(file_path): return os.path.isfile(file_path) file_path = './example.txt' if file_exists(file_path): print(f'{file_path} exists') else: print(f'{file_path} does not exist') try: with open(file_path) as file: print('File exists') except FileNotFoundError: print('File does not exist') |
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!