How to check if a file exist in Python?


In Python, there are multiple ways to check if a file or directory exists or not. For example, exists() is a method used for this purpose.

While working with python you may have the situation where first you want to check if a file exists on your system. If exists then open it otherwise create a new file and then open it for writing output.

In this article, we will discuss different ways to check if a file exists in Python or not.

Check if a file exists with Python try-except block

This is one of the easiest ways to check if a file exists on your system or not. This doesn’t require importing a module in Python code. You need to open a file if you want to perform some action on it.

Now see the given Python code –

try:
    with open('filename.txt') as f:
        print(f.readlines())
# Write code to do something with opened file
except IOError:
     print("File can't be accessed")

In this example, a simple try-except block is used to open a file and perform operations with it. If the file not found IOError exception will be raised and statements under except block will get executed.

Using with keyword while opening the file ensures the file is properly closed after the file operation completed.

Check if a file exists in Python using os.path.exists() method

The os.path module provides some useful functions on pathname. You can quickly check if a file or directory exists on your system by using the path.exists() method.

You can see the usage of this method in the example below.

import os.path

if os.path.exists('filename.txt'):
     print ("File exist")
else:
     print ("File not found")

This method will return True if the file or directory passed in the method exists otherwise it will return False.

Another method in os.path to check if a file exists or not is isfile(). If the argument passed to it is a file or symlink to a file this method will return True otherwise it will return False.

Using pathlib module to check if a file exists in Python or not

The pathlib module was first included in Python 3.4 so using this way on an older version of Python will not work. It is an object-oriented interface to the filesystem and provides a more intuitive method to interact with the filesystem.

Now see the example to use it Python code –

from pathlib import Path

if Path('filename.txt').is_file():
     print ("File exist")
else:
     print ("File not found")

If the argument passed to Path() is a file or symlink to a file then the is_file() method will return True otherwise, it will return False.

Conclusion

Now you know how to check if a file exists in Python. If you have a query then write us in the comments below.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.