Explore Courses Blog Tutorials Interview Questions
+1 vote
in Python by (3.4k points)
edited by

Can we check the existence of a file without using try statement in Python?

4 Answers

0 votes
by (46k points)
edited by

You can use os.path.exists function:

import os.path

For both files and directories this will return True  , Alternatively you can also use the following command to test a file specifically and it follows a symlinks.


0 votes
by (106k points)
edited by

In Python, there are many ways to do so, like using built-in functions or by using Python standard library.

Option 1:-

open() and try...except

  • It is a Pythonic way of checking whether a file exists without exception: You simply try to open the file with the built-in open() function:
  • If the file exists without exception it will return the message that files found and if the file doesn’t exist then it will raise FileNotFoundError.

Here is an example that tells this technique:-


    f = open('abc.txt')


except FileNotFoundError:

    print('File does not exist')

  • Here I am using the close() method on the file object to release the underlying file handle. You should make it practice when dealing with the files in Python.
  • If the file is not closed than handling it explicitly, it is difficult to know when exactly the file will be closed automatically by the Python at runtime. This makes your programs run less efficiently. 
  • open() and a try...except clause has some advantages when it comes to file handling in Python. It can help you avoid bugs caused by file existence race conditions:

Option 2:-


This library is included in Python 3.4 and above version using this module is much easier to handle the exception.

This module provides helper functions for many file system operations, finding out whether a path points to a file or a directory.

To check whether a path points to a valid file you can use the path.exist()method. To find out whether a path is a file, instead of a directory, you’ll want to use path.is_file().

Here is an example:-

import pathlib

path = pathlib.Path('abc.txt')



pathlib provides us a clear object-oriented interface for working with the files. You are no longer working with str objects representing file paths—but instead, you are handling Path objects with relevant methods and attributes.

To know more about this you can have a look at the following video tutorial:-

Learn in detail about Python by enrolling in Intellipaat Python Course online and upskill.

0 votes
by (20.3k points)

Function exists() will return True for directories but isfile() will not return true. So, it depends if you want only the plain files or also directories, then you can use isfile() or exists(). 

Ex: Simple REPL output is as follows:

>>> print os.path.isfile("/etc/password.txt")


>>> print os.path.isfile("/etc")


>>> print os.path.isfile("/does/not/exist")


>>> print os.path.exists("/etc/password.txt")


>>> print os.path.exists("/etc")


>>> print os.path.exists("/does/not/exist")


0 votes
by (20.3k points)

Explanation for the __name__ variable (imho) is as follows:

Try creating the following files like this:


import b



print "Hello World from %s!" % __name__

if __name__ == '__main__':

 print "Hello World again from %s!" % __name__

If you try running them, then you'll get this output:

$ python

Hello World from b!

Here, you can observe that, when a module is imported, Python sets globals()['__name__'] in this module to the module's name. Also, upon import all the code in the module is being run. As the if statement evaluates to False this part is not executed.

$ python

Hello World from __main__!

Hello World again from __main__!

Here you can observe that, when a file is getting executed, Python sets globals()['__name__'] in this file to "__main__". This time, the if statement evaluates to True and is being run.

Related questions

+3 votes
2 answers
0 votes
2 answers
asked May 30, 2019 in Python by Anvi (10.2k points)
+1 vote
1 answer

Browse Categories