How to Check if a File Exists in Python?


To check if a file exists in Python, you can use the os.path module.

Here's an example:

import os

# specify the filename
filename = "example.txt"

# check if the file exists
if os.path.isfile(filename):
    print(f"{filename} exists")
    print(f"{filename} does not exist")

In this example, we first import the os module. Then we specify the filename as a string ("example.txt" in this case).

We use os.path.isfile(filename) to check if the file exists. If it does, we print a message saying that the file exists. If it doesn't, we print a message saying that it doesn't exist.

Latest Questions

python How to Fix ""zsh: command not found: python" Error on MacOS X? python How to Fix "xlrd.biffh.XLRDError: Excel xlsx file; not supported" Error in Pandas? python How to Remove All Whitespace From a Python String?