E-Learning

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:

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:

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.

import  os.path
os.path.isfile (file_path)

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

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

try:   
 with open ('File_name', 'R') at f: 
      use_file (f)
except IOError:
    print 'File does not exist!'

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:

 taddeimania

 

 

 nchafni

 

 

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

Dr. Michael J. Garbade

I, Dr. Michael J. Garbade is the co-founder of the Education Ecosystem (aka LiveEdu), ex-Amazon, GE, Rebate Networks, Y-combinator. Python, Django, and DevOps Engineer. Serial Entrepreneur. Experienced in raising venture funding. I speak English and German as mother tongues. I have a Masters in Business Administration and Physics, and a Ph.D. in Venture Capital Financing. Currently, I am the Project Lead on the community project -Nationalcoronalvirus Hotline I write subject matter expert technical and business articles in leading blogs like Opensource.com, Dzone.com, Cybrary, Businessinsider, Entrepreneur.com, TechinAsia, Coindesk, and Cointelegraph. I am a frequent speaker and panelist at tech and blockchain conferences around the globe. I serve as a start-up mentor at Axel Springer Accelerator, NY Edtech Accelerator, Seedstars, and Learnlaunch Accelerator. I love hackathons and often serve as a technical judge on hackathon panels.

View Comments

Recent Posts

Blockchain in Elections: A Leap Toward Transparent Democracy

In 2024 we're witnessing a critical point in democratic technology: the integration of blockchain and…

3 weeks ago

Win Big with Our Amazon Fire Max 11 & AirPods Pro Giveaway!

We’re thrilled to announce an exciting opportunity for you to win not one but two…

2 months ago

Unleashing Potential: How Education Ecosystem Transforms Learning into Real-World Success

Acquiring practical skills is crucial for career advancement and personal growth. Education Ecosystem stands out…

4 months ago

The Role of Artificial Intelligence in Modern Software Development

Artificial Intelligence (AI) has been making significant strides in various industries, and the software development…

7 months ago

Highest Stable Coin Yields – (W16 – 2024)

Another week to bring you the top yield platforms for three of the most prominent…

8 months ago

LEDU Token OTC Trading

If you hold a large volume of LEDU tokens above 1 million units and wish…

9 months ago