Home » How to check if a file exists in python.

How to check if a file exists in python.

Oracle Java Certification
Java SE 11 Developer (Upgrade) [1Z0-817]
1 Year Subscription
Java SE 11 Programmer I [1Z0-815] Practice Tests
Spring Framework Basics Video Course
Java SE 11 Programmer II [1Z0-816] Practice Tests

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.

Example

import os

file_name=input("Enter File Name: ")

file_exist = os.path.exists(file_name)
print(file_exist)

if file_exist==True:
    print("File exists:",file_name)
else:
    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
False
File does not exist: nofile.txt

>>> %Run fileexists.py
Enter File Name: linecount.txt
True
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