Python

How to check whether a file exists python ?

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 :)

Found a mistake or something out of date? Tell us →

Written by

chandrashekhar

Founder of onlinetutorialspoint.com. Enterprise architect with 15+ years in healthcare technology, designing and running systems on AWS and Azure. Writes about building real things with AI, local AI hardware and cloud certifications.

Keep reading

Ask a question or leave a comment