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

Ad: Are you a blogger? Join our Blogging forum.
Learn PCB Designing: PCB DESIGNING TUTORIAL




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.