How to check if a file or folder exists without getting exceptions ?
This tutorial guides you on how to check if a file or folder exists without getting exceptions. Let’s see various methods for checking whether file or folder existence in Python programming with examples.
Check if a file or folder exists without getting exceptions
There are numerous ways through which you can check file existence using Python programming. In the following method we are going to use python library called pathlib. This python module offers many classes to deal with filesystem paths for different operating systems.
We are going to use Path class most likely in our example in the following section.
Using pathlib and class Path – File/ Folder existence check
For example, to check file existence using pathlib and class Path, you need to call is_file() method as shown below.
from pathlib import Path if Path('sample.txt').is_file(): print ("File exist") else: print ("File not exist")
Output
File not exist
Similarly, you can check directory or folder existence in the following way:
from pathlib import Path if Path('C:/Workspaces/Python/Examples/').is_dir(): print ("Folder exist") else: print ("Folder not exist")
Using os.path library
The os.path library provides some useful functions to deal filesystem paths. For example, the os.path.isfile(path) returns True if path is an existing regular file. Otherise it returns False.
import os.path if os.path.isfile('sample.txt'): print ("File exist") else: print ("File not exist")
Output
File not exist
Similarly to check whether folder/ directory existence try using appropriate methods of os.path library as shown below.
from pathlib import Path if Path('C:/Workspaces/Python/Examples/').is_dir(): print ("Folder exist") else: print ("Folder not exist")
Using try except block
The third approach we are going to see is using try except block to check the file existence as shown below.
try: f = open("sample.txt") except FileNotFoundError: print("File not exist") finally: f.close()
Output
File not exist
You can also use resolve(strict=True) in a try block:
from pathlib import Path fpath = Path("C:/Workspaces/Python/Examples/") try: absolutePath = fpath.resolve(strict=True) except FileNotFoundError: print("File not exist")
Output
File not exist
That’s it. You had learnt three different methods or ways to check whether file or directory exists without getting exceptions using Python programming language tools and libraries.
Hope it helped 🙂
You’ll also like:
- Convert floating point number to fixed point in Python
- What is %matplotlib inline and how to use ?
- Increase the cell width of the Jupyter Notebook in browser
- Add python3 kernel to jupyter IPython notebook ?
- Reset jupyter notebook theme to default theme
- How to change the default theme in Jupyter Notebook ?
- Change the Jupyter Notebook startup folder in Windows & Mac
- To run Jupyter Notebook on Windows from command line
- Run a Jupyter Notebook .ipynb file from terminal or cmd prompt
- Amazon Linux AMI : apt-get command not found
- Remove non-numeric characters from string in Python
- Python program to find the greatest of three numbers
- Putty Fatal Error No supported authentication methods available
- Find which users belongs to a specific group in linux
- Embed HTML within IPython Notebook
- Check if Python Object is a Number ?
- Error: helm install unknown flag: –name
- Install Python 3 on Windows 10 machine
- Convert negative to positive number in Python
- TypeError: a bytes-like object is required, not ‘str’ – Python3
- Extract numbers from a string in python