Is it possible to make a Python program which checks if a file exists, maybe like:

#!/usr/bin/python

if exist 'File.txt':
  print "File.txt exists!"
else:
  print "File.txt does not exist :-("

Obviously the if exist code will fail, as it is not a python command, but is there anything like the above which works?

HTMLperson5
Deleted Member

Look at os.path.exists and os.path.isfile thats dos what you describe.

>>> help(os.path.exists)
Help on function exists in module genericpath:

exists(path)
    Test whether a path exists.  Returns False for broken symbolic links

>>> help(os.path.isfile)
Help on function isfile in module genericpath:

isfile(path)
    Test whether a path is a regular file

Or try/except that is a safe an pythonic way to solve this.

try:
   open()
except IOError as e:
   print 'No file found'

Edited 4 Years Ago by snippsat

from os import path

PATH = "folder_path/file.txt"
if path.exists(PATH) and path.isfile(PATH):
    print "File does exist"
else:
      print "File doesn't exist!"
Comments
best method

if path.exists(PATH) and path.isfile(PATH):

There is no extra value of using both only the latter is enough. But in multitasking conditions, the situation can change between execution of the test of condition and execution of the following statements as they are not 'atomic'. So it is considered more correct to react to missing file in try... except like snippsat showed last.

Edited 4 Years Ago by pyTony

def file_exists(filename):
    '''
    a file exists if you can open and close it
    '''
    try:
        f = open(filename)
        f.close()
        return True
    except:
        return False

HiHe function is ok,but some changes that i think make it better.
Bare except(catch all maybe) i dont like this to much.
And with open() is preferred over open(),no need to close file object and it dos some error checking to.

def file_exists(filename):
    try:
        with open(filename) as f:
            return True
    except IOError:
        return False

Or return the specific error masseage to user.

def file_exists(filename):
    try:
        with open(filename) as f:
            return True
    except IOError as error:
        return 'A problem occurred: {}'.format(error)

Edited 4 Years Ago by snippsat

Nice to use with, not sure when it was introduced? Earlier Python2 version don't have it.
A little simpler:

def file_exists2(filename):
    try:
        with open(filename): return True
    except:
        return False

The only thing you doing is to open a file, there are not too many error choices?

Edited 4 Years Ago by HiHe

with, not sure when it was introduced?

Python 2.7.3 (default, Apr 10 2012, 23:31:26) [MSC v.1500 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> import __future__
>>> dir(__future__)
['CO_FUTURE_ABSOLUTE_IMPORT', 'CO_FUTURE_DIVISION', 'CO_FUTURE_PRINT_FUNCTION', 'CO_FUTURE_UNICODE_LITERALS', 'CO_FUTURE_WITH_STATEMENT', 'CO_GENERATOR_ALLOWED', 'CO_NESTED', '_Feature', '__all__', '__builtins__', '__doc__', '__file__', '__name__', '__package__', 'absolute_import', 'all_feature_names', 'division', 'generators', 'nested_scopes', 'print_function', 'unicode_literals', 'with_statement']
>>> print(__future__.with_statement)
_Feature((2, 5, 0, 'alpha', 1), (2, 6, 0, 'alpha', 0), 32768)
>>> 

It was functioning with from __future__ import in version 2.5.0 and from 2.6.0 onwards it does not need import.

Nice to use with, not sure when it was introduced?

In python 2.5 september 19, 2006.

Bare "except:", with no exception specified is nasty because it can easily hide bugs.

except: #Dont do this

To use your code as example.

def file_exists(filename):
    '''
    a file exists if you can open and close it
    '''
    try:
        f = ope(filename) # misspelled "open"
        f.close()
        return True
    except:
        return False 

print file_exists('somefile.txt')

The misspelled "open" triggers a NameError,which is caught by the except clause.
So funcion return False,so it hide the real problem that there is NameError.
except IOError will only catch IOError and show that NameError is the problem.

When people see bare "except:" in code they can complain about it.
http://python.6.n6.nabble.com/issue4788-two-bare-quot-except-quot-clauses-are-used-in-the-ssl-module-td701941.html

Edited 4 Years Ago by snippsat

Comments
I totally agree

Hi again, guys.

Thanks for all your contributions; I really appreciate it, I got this to work at the end :D

This question has already been answered. Start a new discussion instead.