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:
1 |
import os.path |
This command will allow you to access the file you want. We can now proceed with the search, using one of the following:
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:
1 2 |
import os.path os.path.exists (file_path) |
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.
1 2 |
import os.path os.path.isfile (file_path) |
Below we have a comparison between the two functions, showing the difference between them:
1 2 3 4 5 6 7 8 9 10 11 12 |
print os.path.isfile ("/ Bla / blebli") True print os.path.isfile ( "/ Bla" ) False print os.path.isfile ( "/ We / have / a_problem" ) False print os.path.exists ( "/ Bla / blebli" ) True print os.path.exists ( "/ Bla" ) True print os.path.exists ( "/ We / have / a_problem" ) False |
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
1 2 3 4 5 |
try: with open ('File_name', 'R') at f: use_file (f) except IOError: print 'File does not exist!' |
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:
Another cool way to find out interesting things about Python is to access our project page!