Check if a file or folder exists without getting exceptions

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

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:

References

Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments