Menu Close

How to check whether a file exists without exceptions with Python?

Sometimes, we want to check whether a file exists without exceptions with Python.

In this article, we’ll look at how to check whether a file exists without exceptions with Python.

How to check whether a file exists without exceptions with Python?

To check whether a file exists without exceptions with Python, we can use the os.path.isFile method.

For instance, we write:

import os.path
fname = './foo.txt'
os.path.isfile(fname) 

fname is a file path string.

If the file doesn’t exist at the fname path, then it returns False.

Conclusion

To check whether a file exists without exceptions with Python, we can use the os.path.isFile method.

Posted in Python, Python Answers