How to check whether a file exists or not in python?

+2 votes
asked Aug 9, 2016 by Hitesh Garg (352 points)  

I have to parse a file if it exists in the current directory. How do I do it and what is the simple and most efficient way to do this?

1 Answer

+2 votes
answered Aug 9, 2016 by Rahul Singh (553 points)  
selected Aug 9, 2016 by Hitesh Garg
Best answer

What you are looking at can be done easily by using isfile function of os.path.
Official documentation of os.path.isfile - Return True if path refers to a directory entry that is a symbolic link. Always False if symbolic links are not supported by the Python runtime.

It can be done as follows -

>>> import os

>>> os.path.isfile
<function isfile at 0x0205B1F0>

>>> os.path.isfile('C:\Python27\README.txt')

>>> os.path.isfile('README.txt')

>>> os.path.isfile('./README.txt')

>>> os.path.isfile('FAKENAME.txt')

Above code is the output of python.exe and there is a file README.txt adjacent to it.
Second command is just to show that os.path.isfile is a function.
We can pass the complete path or the absolute path to this function(as show in command 3, 4 and 5).

commented Dec 2, 2016 by pepin (10 points)  
I found an update guide on how to check if a file exists with python here:
Welcome to Codingeek Q&A, where you can ask questions and receive answers from other members of the community.