Learn Python – How To Check Whether a File Exists?

How to tell if a file exists using Python? To answer this question, we need to know how this programming language “sees” the files.


Accessing a file in Python

To grant access to your program to all computer files, you need to import the module os into Python. It provides information about the computer’s operating system. We are more interested, specifically, in the file directory, accessed by os.path. The command you will use looks like this:

This command will allow you to access the file you want. We can now proceed with the search, using one of the following:



Get More Benefits With LiveEdu Pro

Using the function os.path.exists

When you want to know if a file exists, you can use the function os.path.exists. A code using this function is similar to this:

This code will return “True” or “False”.  We have a problem, however, because  it  returns true for directories and files. How to know if the path is a file?


Using the function  os.path.isfile

This function checks if the path stated is really a file, not a directory.

Below we have a comparison between the two functions, showing the difference between them:

The previous functions only check if the file exists. And if after this verification the file is deleted or created by another function? This can become a security problem in your program, known as “race condition“. There is, therefore, a safer method to check it, using the option below:


Using the function try / except

This function tries to open the file as read-only (the ‘r’ after the file name). If the file does not exist, it returns the error message. Please remember that there are other possible errors, such as access permission to read the file, that you should consider before declaring that the file does not exist. You will need to catch all exceptions to be sure that the file doesn’t exists.

Do you know other different ways to check if a file exists in Python? Share it in the comments area below.

Now that you’ve seen these possible answers to this question, how about exploring more? You can check on our website videos about Python. Below are some examples:

You can also follow some of our broadcasters who program in Python, as below:

python import file livecoding.tv taddeimania



python import file livecoding.tv nchafni



Another cool way to find out interesting things about Python is to access our project page!

LiveEdu Pro
Check Out the LiveEdu Pro Subscription

  • Kevin Rodger

    Another good article on Python. Understood the concept in 10 minutes.

Read previous post:
How to call an external command in Python- (1)
Learn Python – How To Call an External Command?

  Many times is necessary that Python interacts with the computer's operating system where it is running. For example, to...