Lokasi ngalangkungan proxy:   [ UP ]  
[Ngawartoskeun bug]   [Panyetelan cookie]                
Skip to content
No results
  • About AskPython
  • Blog
  • Contact Me
  • Free Online Developer Tools Hub
  • Home
  • Meet the Team
  • Privacy Policy
  • Python
  • Python Course for Beginners Online FREE
  • Python Tutorial – Mega Index
  • Terms and Conditions

🚀 Supercharge your YouTube channel's growth with AI.

Try YTGrowAI Free
  • Home
  • Blog
  • About AskPython
  • Python Course
  • Start Here

Check if a File Exists in Python

  • SnehSneh
  • February 13, 2020
  • Python Modules
Check if a File Exists in Python

Introduction

How to check if a file exists in Python? We have learned to perform various operations on a file in our previous file handling tutorials including reading, writing, deleting as well as copying a file in Python. But, before we perform any of these operations on a file, checking whether the file already exists or not is necessary.

If a file does not exist, then neither can we read from it nor copy or delete it. Even while writing, the user may want to check the existence of a file to avoid overwriting information.

Let us proceed into the topic and look at some methods to check the existence of a file.

Methods to check if a file exists in Python

We can check if a file exists in Python using the different methods mentioned below.

1. Using pathlib module

The pathlib module in Python comes with some interesting methods like is_file(), is_dir(), exists(), etc. Let us look at some examples one by one:

import pathlib
path = pathlib.Path('file.txt')
print("pathlib-exists()---->",path.exists())
print("pathlib-is_file()---->",path.is_file())
print("pathlib-is_dir()---->",path.is_dir())

Output:

Pathlib Output
pathlib Output
  • pathlib.Path() returns a path object which leads to the file name specified, which is stored in the variable ‘path‘,
  • pathlib.exists() method checks whether the path provided leads to a valid file or not. In our case, as file.txt’s path exists, the outcome is true.
  • is_file() method, on the other hand, checks whether the path object is the file. Which in our case is true as we can see in the output.
  • is_dir() method checks if the supplied path is any directory. Here, since our file.txt path is not a directory we get the above output.

2. Using the os module

One of the vastly used methods for checking file existence is the os.path module from the standard python library. It comes with some basic methods like isfile() and exists() similar to that of the pathlib module. Let take a closer look at one example:

import os.path
print("os.path-exists()---->",os.path.exists('file.txt'))
print("os.path-isfile()---->",os.path.isfile('file.txt'))

Output:

Os Path Output
os.path Output
  • Similar to the pathlib modules exists() and is_file() methods, os.exists() as well as os.isfile() also do similar checking respectively.
  • The only difference being the fact that the pathlib module brings in some great object-oriented approach and treats the path as a path object instead of a string(in case of os module).

3.Using exception handling

Let’s now have a look at a few different methods to check if a file exists in Python using exceptions.

This time we are going to use the built-in open() function to open a file and check for an exception which if raised, will confirm that the file doesn’t exist or is inaccessible. For example:

My_file=open('file.txt')
try:
    My_file.close()
    print("File found!")
except FileNotFoundError:
    print("Files couldn't be opened!")

Output:

File found!
  • In the above-given code since file.txt existed in our system, FileNotFoundError isn’t raised and successfully the file gets closed.

Again, when no-file.txt doesn’t exist on our machine:

try:
    My_file=open('no-file.txt')
    My_file.close()
    print("File found!")
except FileNotFoundError:
    print("Files couldn't be opened!")

Output:

File Not Found Exception
FileNotFoundError Exception
  • So we can clearly see that when the file isn’t found the exception FileNotFoundError is raised.

Further, the same task can be achieved with the IOError which checks if the file being opened is readable and accessible to the program. For example, consider the following code snippet:

try:
    My_file = open('no-file.txt')
    My_file.close()
    print('File is found!')
except IOError:
    print('IOError encountered!')

Output:

IOError
IOError

References

  • https://stackoverflow.com/questions/82831/how-do-i-check-whether-a-file-exists-without-exceptions
  • https://docs.python.org/3/library/pathlib.html
  • https://docs.python.org/3/library/os.html

Sneh
Sneh
Articles: 36
How to Convert List to String in Python – Multiple Methods
Previous Post How to Convert List to String in Python - Multiple Methods
Next Post Python json Module
Python json Module

Related Posts

np.linalg.eig: Eigenvalues and Eigenvectors

np.linalg.eig: Eigenvalues and Eigenvectors

  • November 30, 2026
np.sin() in NumPy: Radians, Arrays, and Examples

How to Use np.sin() in NumPy

  • November 30, 2026
cv2.imread: Load Images with OpenCV

cv2.imread: Load Images with OpenCV

  • November 30, 2026

Partner Websites

  • GoLangDocs
  • LinuxForDevices
  • CodeForGeek

Popular Categories

  • Python Programming
  • Python Modules
  • OOPS in Python
  • Python Programming Examples
  • Strings in Python

Hall of Fame

  • Python Programming
  • OOPS in Python
  • Creating Python Modules
  • Args and Kwargs in Python
  • Python Dictionary (Dict) Tutorial
  • Python List – 15 Things You MUST Know
  • Python Set – Things You MUST Know
  • Python String Functions: Methods by Task

Important Links

  • Home
  • Python Course
  • Start Here
  • Blog
  • About AskPython
Latest posts
  • np.linalg.eig: Eigenvalues and Eigenvectors
  • What Does %s Mean in a Python Format String?
  • How to Use np.sin() in NumPy
  • cv2.imread: Load Images with OpenCV
  • pd.read_json: Read JSON Into a DataFrame

Copyright © 2026 - AskPython. All rights reserved.