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

+2 votes
154 views
asked Aug 9, 2016 by Hitesh Garg (135 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 10, 2016 by Rahul Singh (163 points)  
selected Aug 10, 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')
True

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

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

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

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 3, 2016 by pepin (10 points)  
I found an update guide on how to check if a file exists with python here: http://tutorials.technology/tutorials/08-How-to-check-that-file-exists-with-Python.html
...