python os check for file code example

Example 1: python check if file exists

import os

os.path.exists("file.txt") # Or folder, will return true or false

Example 2: python os if file exists

import os.path

if os.path.isfile('filename.txt'):
    print ("File exist")
else:
    print ("File not exist")

Example 3: python with statement file does not exist exception

import os

PATH = './file.txt'
if os.path.isfile(PATH) and os.access(PATH, os.R_OK):
    print("File exists and is readable")
else:
    print("Either the file is missing or not readable")

Example 4: check if a file exists

>>> import os
>>> os.path.isfile("d:\\Package1\\package1\\fibo.py")
True
>>> os.path.isfile("d:/Package1/package1/fibo.py")
True
>>> os.path.isfile("d:\\nonexisting.txt")

Tags:

Misc Example