Python

How to check a file exists in Python

It is necessary to find out any file exists or not for many programming purposes. For example, it is important to know the file exists before opening a file for reading otherwise it displays an error message. If you want to prevent overwriting any existing file then you have to find out the file already exists or not before writing. There are many built-in functions in python to check the existence of any file. The different ways to check any file exists or not are shown in this tutorial.

Check if file exists using os.path.isfile():

os module contains different methods to check any file or directory exists or not. The following example the os.path.isfile() method of os module is used to check the file exists or not. Here, the user can provide only the filename if the file exists in the current location or the filename with path as input. Next, os.path.isfile() method is used to check the path is valid or not and the provided filename is the file or a symlink of a file.

#!/usr/bin/env python3
# Import os module
import os

# Take a filename
fn = input("Enter a filename to read:\n")
# Check the file exist or not
if os.path.isfile(fn):
   # print the message if file exists
   print ("File exists")
else:
   # Print the message if the file does not exist
   print ("File does not exist")

Output:

In the first input, an invalid filename is given as input and the output shows ‘File does not exist’. In the second input, a valid filename is given as input and the output shows ‘File exists’.

Check if file exists using os.path.exists():

In the following script, os.path.exists() method is used to check the existence of any file. The method is used to test any path is a file, directory, or symlink. Here, it works similarly to the previous example.

#!/usr/bin/env python3
# Import os module
import os

# Take a filename
fn = input("Enter a filename to read:\n")
# Check the file path exist or not
if os.path.exists(fn):
    # print the message if path exists
    print ("File exists")
else:
    # Print the message if the file path does not exist
    print ("File does not exist")

Output:

In the first input, an invalid file path is given as input and the os.path.exists() returned false. The output shows ‘File does not exist’. In the second input, a valid file path is given as input and the os.path.exists() returned true. The output shows ‘File exists’.

Check if file exists using is_file() of pathlib module:

pathlib module is another useful module of python to check any file or directory exists or not. It contains various methods like os module to test the path, file, or directory. The following script shows the use of is_file() method of this module to check the file exists or not. The filename will be taken from the user like the previous example. The output will be displayed based on the return value of is_file() method. If the file exists then the

content of the file will display.

#!/usr/bin/env python3
from pathlib import Path
# Take a filename
fn = input("Enter a filename to read:\n")

if Path(fn).is_file():
   # print the message if file path exists
   print ("\nFile exist")
   print("The content of the file shown below:" )
   # Open the file for reading
   fh = open(fn)
   # Print the file content
   print(fh.read())
else:
   # Print the message if the file path does not exist
   print ("File does not exist")

Output:

In the first input, an invalid filename is given as input and the output shows ‘File does not exist’. In the second input, a valid filename is given as input and the output shows ‘File exists’ and the content of the file is displayed.

Check if file exists using exists() of pathlib module:

pathlib module also contains exists() method like the os module. The following example shows the use of this method. If the file path exists then it will display the content of the file.

#!/usr/bin/env python3
import pathlib
# Take a filename
fn = input("Enter a filename to read:\n")
path = pathlib.Path(fn)
if path.exists():
  # print the message if file path exists
  print ("\nFile exist")
  print("The content of the file shown below:" )
  # Open the file for reading
  fh = open(fn)
  # Print the file content
  print(fh.read())
else:
  # Print the message if the file path does not exist
  print ("File does not exist")

Output:

In the first input, an invalid file path is given as input and the output shows ‘File does not exist’. In the second input, a valid file path is given as input and the output shows ‘File exists’ and the content of the file is displayed.

Check if file exists using exception handling:

Using the python exception handling feature, you can easily check the file exists or not. The following script shows how you can check the file exists without importing any module. After taking the filename, the file will be opened in the try block. If the file does not exist then it will generate an exception and print a custom error message.

#!/usr/bin/env python3
# Take a filename
fn = input("Enter a filename to read:\n")
try:
   # Open the file for reading
   fileHandler = open(fn)
   # Print the following message if no exception occurs
   print("File exists")
   # close the file
   fileHandler.close()
except FileNotFoundError:
   # Print the following message if any error occurs
   print("File is not exist or accessible")
finally:
   # print the termination message
   print("End of the program")

Output:

The following output will appear if an invalid filename is given and a valid filename is given.

Conclusion:

The various ways of checking the file exists or not in python are described in this tutorial using different types of examples. Python modules are used in some scripts and exception handling is used in a script here. The user can follow any of the ways for checking the file exists or not.

About the author

Fahmida Yesmin

I am a trainer of web programming courses. I like to write article or tutorial on various IT topics. I have a YouTube channel where many types of tutorials based on Ubuntu, Windows, Word, Excel, WordPress, Magento, Laravel etc. are published: Tutorials4u Help.