Home ยป How to check if a file exists in python.

How to check if a file exists in python.

In this example we will show you how to check if a file exists using python

This checks whether a file exists or not using the exists() function of the os module.


import os

file_name=input("Enter File Name: ")

file_exist = os.path.exists(file_name)

if file_exist==True:
    print("File exists:",file_name)
    print("File does not exist:",file_name)

When you run this you will see something like this

>>> %Run fileexists.py
Enter File Name: nofile.txt
File does not exist: nofile.txt

>>> %Run fileexists.py
Enter File Name: linecount.txt
File exists: linecount.txt

You may also like

Leave a Comment

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More