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

+2 votes
502 views
asked Aug 9, 2016 by Hitesh Garg (355 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?

2 Answers

+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')
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 2, 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
+1 vote
answered Feb 12 by leneborma (20 points)  
import os
dirname = "temp"
filename = "my_file"
#check directory exists
if(os.path.exists(dirname)):
print("Directory Exists")
else:
print("Directory does not exists")

#check file exists
if(os.path.exists(filename)):
print("File Exists")
else:
print("File does not exists")

Full source...file exist

...