Here we will see how to check whether a file exists python.

Check whether a file exists python?

Python os module helps us to access the underlying folder structure. By gaining this advantage lets try to check whether a file or directory exists or not within a given directory.

1. os.path.exists()

os.path.exists() function takes the path as a parameter and returns a boolean value – True in case of the file exists else it returns False.

import os

if __name__ == '__main__':
    file_path = "C:\\Users\\Lenovo\\sample.txt";
    print("isFile Exists - "+os.path.exists(file_path))

Output:

True

2. pathlib.Path.exists()

We can also get the file existence using pathlib package like the os module.

import pathlib

if __name__ == '__main__':
    file_path = "C:\\Users\\Lenovo\\sample.txt";
    print(pathlib.path.exists(file_path))

Output:

True

References:

Happy Learning 🙂