EDUCBA Logo

EDUCBA

MENUMENU
  • Explore
    • EDUCBA Pro
    • PRO Bundles
    • Featured Skills
    • New & Trending
    • Fresh Entries
    • Finance
    • Data Science
    • Programming and Dev
    • Excel
    • Marketing
    • HR
    • PDP
    • VFX and Design
    • Project Management
    • Exam Prep
    • All Courses
  • Blog
  • Enterprise
  • Free Courses
  • Log in
  • Sign Up
Home Software Development Software Development Tutorials File Handling Python Tutorial Python Check if File Exists
 

Python Check if File Exists

Updated March 2, 2023

Python Check if File Exists

 

 

Introduction to Python Check if File Exists

In Python Check, if File Exists, there are some built-in functions to determine whether the file exists. It is important to check if the file exists before uploading any data on the disk or to avoid overwriting the existing file. Unfortunately, there are few built-in functions in the Python standard library. Therefore, one of the simplest ways to check whether a file exists is to try to open the file, as this does not require any built-in modules or standard library.

Watch our Demo Courses and Videos

Valuation, Hadoop, Excel, Mobile Apps, Web Development & many more.

How to Check if File Exists in Python?

There are different ways to check if a file exists in Python. Let us see one by one with examples:

  • os. path.exists()
  • os. path.isfile()

In Python, these two methods are common ways to check file existence. The methods exist(), and isfile() are from the os. path module in the Python standard library. So before using it, we have to import this module to use in our codes. This module is available in both Python 2 and 3 versions. So usually, both these methods check if the file exists or not and return the result in either true if the file exists or false if the file does not exist. Let us consider an example:

Example #1

Let us check with the os. path.isfile() method:

Code:

import os.path
f1 = open('Text.txt', 'w')
f1.write("Educba Training")
f1.close()
if os.path.isfile('Text.txt'):
print ("File exist")
f2 =open('Text.txt','r')
print(f2.read())
f2.close()
else:
print ("File not exist")

Output:

Python Check exits - Example1

Example #2

If the file does not exist, then it will have:

Code:

import os.path
if os.path.isfile('Text.txt'):
print ("File exist")
else:
print ("File does not exist")

Output:

Python Check exits - Example2

os. path. Exists () method also works the same as the isfile() method in the above code. However, instead of isfile(), you can use exists() method as its results are the same as the above code returns. So these two methods only check if files exist, but not if the program has access. So similarly, you can use these even to check if directories exist or not using exists() and isdir() methods.

Another option is to use the most common built-in method, the open() function with try and except block. Usually, the method open() itself describes as it can open a file it can be a new file. Still, if an open file exists, it may give an error saying no such file or directory for writing to the file.

Example #3

Code:

open('Text.txt')

Output:

Python Check exits - Example3

So to avoid this, we used to raise the exception to handle such errors. We can use this to raise the FileNotFoundError exception that can be handled or IOError. So in the above code, we have got IOError which can be handled by the try and except block as shown below to check or to say that file does not exist. In this option, it is only used to handle the error when the file does not exist; otherwise, if the file exists, it will not give any such error. So this attempt is to check the file for both readable and accessible, which allows you to check for the existence of the file and is also accessible simultaneously.

Example #4

Code:

try:
f = open('Text.txt')
f.close()
except IOError:
print('File does not exist')

Output:

Python Check exits - Example4

pathlib.path.exists(): This is another option to check if the file exists or not; this method is available in Python 3.4 and above versions only. This method deals with file system paths that provide an object-oriented interface. So this is another Python standard library that again has exists() and is_file() method in this module, which provides an abstraction for many file system operations. This module includes these two helper functions for existence checks and is used to find whether a path points to a file or a directory. So if you want to check if the path points to a file, we have to use path.exists(), and if we want to check if the path is the file or symbolic link instead of the directory, we have to use the path.is_file() method. So we can say this option is similar to the first option for checking the file using the os. path module of the Python standard library.

Example #5

Let us consider an example:

Code:

import pathlib
file = pathlib.Path("Text1.txt")
if file.exists ():
print ("File exist")
else:
print ("File does not exist")

Output:

 Example5

Example #6

If the file exists, then we can check in the following code:

Code:

import pathlib
f1 = open('Text1.txt', 'w')
f1.write("Educba Training")
f1.close()
file = pathlib.Path("Text1.txt")
if file.exists ():
print ("File exist")
f2 =open('Text1.txt','r')
print("File contains:",f2.read())
f2.close()
else:
print ("File does not exist")

Output:

Example 6

Similarly we can use is_file() function can be used instead of exists() function in the above code. As this option and the first option are the same, this option is better as it provides a cleaner object-oriented interface for working with the file system. We can make file handling code more readable and more maintainable in this option. Another difference is that the pathlib module is available for Python 3.4 and above versions, whereas the os. Path module is available for Python 2 versions.

Conclusion

So the above article describes the different ways of checking the file’s existence. So checking the file existence is important because whenever we want to upload ay content to the file and if the file does not exist, then it gives an error which can be handled using the second option in the above article, that is to handle IOError; otherwise, sometimes it is really necessary to check the file existence as to avoid overwriting to the file contents. So to check if the file exists, the simplest way is to use the open() function as we did in the above article, other modules, or standard libraries like os. Path and pathlib. The path is used in Python, which both have to exist () and isfile() helper functions in this module for file check existence.

Recommended Articles

This is a guide to Python Check if File Exists. Here we discuss the introduction, How to Check if the File Exists in Python and the Examples of Python Check File. You can also go through our other suggested articles to learn more –

  1. Python Ternary Operator
  2. Identity Operators in Python
  3. Lowercase in Python
  4. Multiple Inheritance in Python

Primary Sidebar

Footer

Follow us!
  • EDUCBA FacebookEDUCBA TwitterEDUCBA LinkedINEDUCBA Instagram
  • EDUCBA YoutubeEDUCBA CourseraEDUCBA Udemy
APPS
EDUCBA Android AppEDUCBA iOS App
Blog
  • Blog
  • Free Tutorials
  • About us
  • Contact us
  • Log in
Courses
  • Enterprise Solutions
  • Free Courses
  • Explore Programs
  • All Courses
  • All in One Bundles
  • Sign up
Email
  • [email protected]

ISO 10004:2018 & ISO 9001:2015 Certified

© 2025 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
Loading . . .
Quiz
Question:

Answer:

Quiz Result
Total QuestionsCorrect AnswersWrong AnswersPercentage

Explore 1000+ varieties of Mock tests View more

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

By continuing above step, you agree to our Terms of Use and Privacy Policy.
*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you

EDUCBA Login

Forgot Password?

🚀 Limited Time Offer! - 🎁 ENROLL NOW