Home » Python

Python | Check if a file exists or not?

In this tutorial, we are going to learn how to check whether a file exists or not in python?
Submitted by IncludeHelp, on December 30, 2018

The task is to check whether a file exists or not?

Before continuing to the tutorial, please note that – there are some of the separate functions which are used to check whether a file or directory exists or not. So you have to make sure what you want to check a file or a directory.

To use the functions, we have to import the "os" module, the functions are:

  1. os.path.isfile(): To check whether a file exists or not.
  2. os.path.isdir(): To check whether a directory exists or not.
  3. os.path.exists(): To check for both either a file or a directory.

So, if you are not sure about the file or directory, I would recommend using "os.path.exists()" function to avoid the error.

Example:

In this example, we are checking a file "file.txt" and if it does not exist, we will create and close the file and then again check for the same file.

# import statement
import os

# checking file
if not(os.path.exists("file.txt")):
	print("File does not exist")
	# creating & closing file 
	fo = open("file.txt","wt")
	fo.close();
else:
	print("File exists")

# checking again
if os.path.exists("file.txt"):
	print("Now, file exists")
else:
	print("File does not exist")

Output

File does not exist
Now, file exists


Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.