How To Check Whether A File Exists Using Python? – POFTUT

How To Check Whether A File Exists Using Python?


Python programming language provides different ways to check file existence. In this tutorial we will examine functions like isFile() and exists() to check file existence.

Import os.path Module

In order to use isFile() and exists() functions we need to import the os.path module which contains these functions.

import os.path

isFile() Method

isfile() is a function in os.path library. This function will be return true if the file is regular file and exists. As we can see following example we should provide the path and name of the file.

import os.path
if(os.path.isfile("/etc/passwd")):
    print("/etc/passwd exists")
isFile() Method
isFile() Method

exists() Method

exists is os.path method too and returns true if file exists. We will provide /etc/passwd as parameter to the exists() function like below.

import os.path
if(os.path.exists("/etc/passwd")):
    print("/etc/passwd exists")
exists() Method
exists() Method

 

How To Check Whether A File Exists Using Python? Infografic

 

LEARN MORE  HTTP Status 503 Error Code and How To Fix It?

Leave a Comment