How do I check whether a file exists, without using the try statement?

share|improve this question
    
Just to add to the confusion, it seems that the try: open() approach suggested previously doesn't work in Python, as file access isn't exclusive, not even when writing to files, c.f. stackoverflow.com/questions/186202/…. – Tilman Nov 22 '10 at 16:19
1  
I suppose a good reason to check for the presence of a file like you are asking is if the mere presence sends a message all by itself. And that there is no intention of reading it, eh? – SDsolar Nov 2 '17 at 5:07
    
@Tilman open() is not appropriate since it does not scale, would require closing the file and has the side effect of changing the last access time of the file.. – ShpielMeister Dec 16 '17 at 4:47

41 Answers 41

This is the simplest way to check if a file exists. Just because the file existed when you checked doesn't guarantee that it will be there when you need to open it.

import os
fname = "foo.txt"
if os.path.isfile(fname):
    print("file does exist at this time")
else:
    print("no such file exists at this time")
share|improve this answer
7  
As long as you intend to access the file, the race condition does exist, regardless of how your program is constructed. Your program cannot guarantee that another process on the computer has not modified the file. It's what Eric Lippert refers to as an exogenous exception. You cannot avoid it by checking for the file's existence beforehand. – Isaac Supeene Nov 23 '14 at 18:37
    
While it's technically true that a race condition exists, the odds can be so vanishingly small that it can be ignored in most situations, especially in single-threaded programs, which most Python programs tend to be. – Mike Collins Jan 19 '17 at 18:31
    
@MikeCollins - The single-threadedness of Python is irrelevant if the file is being managed by a different process. – MrWonderful yesterday

2017 / 12 / 22:

Although almost every possible way has been listed in (at least one of) the existing answers (e.g. Python 3.4 specific stuff was added), I'll try to group everything together.

Note: every piece of Python standard library code that I'm going to post, belongs to version 3.5.3 (doc quotes are version 3 specific).

Problem statement:

  1. Check file (arguable: also folder ("special" file) ?) existence
  2. Don't use try/except/else/finally blocks

Possible solutions:

  1. [Python]: os.path.exists(path) (also check other function family members like os.path.isfile, os.path.isdir, os.path.lexists for slightly different behaviors)

    os.path.exists(path)
    

    Return True if path refers to an existing path or an open file descriptor. Returns False for broken symbolic links. On some platforms, this function may return False if permission is not granted to execute os.stat() on the requested file, even if the path physically exists.

    All good, but if following the import tree:

    • os.path - posixpath.py (ntpath.py)

      • genericpath.py, line ~#20+

        def exists(path):
            """Test whether a path exists.  Returns False for broken symbolic links"""
            try:
                st = os.stat(path)
            except os.error:
                return False
            return True
        

    it's just a try/except block around [Python]: os.stat(path, *, dir_fd=None, follow_symlinks=True). So, your code is try/except free, but lower in the framestack there's (at least) one such block. This also applies to other funcs (including os.path.isfile).

    1.1. [Python]: pathlib.Path.is_file()

    • It's a fancier (and more pythonic) way of handling paths, but
    • Under the hood, it does exactly the same thing (pathlib.py, line ~#1330):

      def is_file(self):
          """
          Whether this path is a regular file (also True for symlinks pointing
          to regular files).
          """
          try:
              return S_ISREG(self.stat().st_mode)
          except OSError as e:
              if e.errno not in (ENOENT, ENOTDIR):
                  raise
              # Path doesn't exist or is a broken symlink
              # (see https://bitbucket.org/pitrou/pathlib/issue/12/)
              return False
      
  2. [Python]: os.access(path, mode, *, dir_fd=None, effective_ids=False, follow_symlinks=True) whose behavior is close to os.path.exists (actually it's wider, mainly because of the 2nd argument)

    • user permissions might restrict the file "visibility" as the doc states:

      ...test if the invoking user has the specified access to path. mode should be F_OK to test the existence of path...

    os.access("/tmp", os.F_OK)
    

    Personally, I prefer this one because under the hood, it calls native APIs (via "${PYTHON_SRC_DIR}/Modules/posixmodule.c"):

    Note: calling native APIs is also possible via [Python]: ctypes — A foreign function library for Python, but in most cases it's more complicated.

    (Win specific): Since msvcr*(vcruntime*) exports a [MSDN]: _access, _waccess function family as well, here's an example:

    Python 3.5.3 (v3.5.3:1880cb95a742, Jan 16 2017, 16:02:32) [MSC v.1900 64 bit (AMD64)] on win32
    Type "help", "copyright", "credits" or "license" for more information.
    >>> import os, ctypes
    >>> ctypes.CDLL("msvcrt")._waccess(u"C:\\Windows\\System32\\cmd.exe", os.F_OK)
    0
    >>> ctypes.CDLL("msvcrt")._waccess(u"C:\\Windows\\System32\\___cmd.exe", os.F_OK)
    -1
    

    Notes:

    • Although it's not a good practice, I'm using os.F_OK in the call, but that's just for clarity (its value is 0)
    • I'm using _waccess so that the same code works on Python3 and Python2 (in spite of unicode related differences between them)
    • Although this targets a very specific area, it was not mentioned in any of the previous answers


    The Lnx(Ubtu(16 x64)) counterpart as well:

    Python 3.5.2 (default, Nov 17 2016, 17:05:23)
    [GCC 5.4.0 20160609] on linux
    Type "help", "copyright", "credits" or "license" for more information.
    >>> import os, ctypes
    >>> ctypes.CDLL("/lib/x86_64-linux-gnu/libc.so.6").access(b"/tmp", os.F_OK)
    0
    >>> ctypes.CDLL("/lib/x86_64-linux-gnu/libc.so.6").access(b"/tmp1", os.F_OK)
    -1
    

    Notes:

    • Instead hardcoding libc's path ("/lib/x86_64-linux-gnu/libc.so.6") which may (and most likely, will) vary across systems, None (or the empty string) can be passed to CDLL constructor (ctypes.CDLL(None).access(b"/tmp", os.F_OK)). According to [man]: DLOPEN(3):

      If filename is NULL, then the returned handle is for the main program. When given to dlsym(), this handle causes a search for a symbol in the main program, followed by all shared objects loaded at program startup, and then all shared objects loaded by dlopen() with the flag RTLD_GLOBAL.

      • Main (current) program (python) is linked against libc, so its symbols (including access) will be loaded
      • This has to be handled with care, since functions like main, Py_Main and (all the) others are available; calling them could have disastrous effects (on the current program)
      • This doesn't also apply to Win (but that's not such a big deal, since msvcrt.dll is located in "%SystemRoot%\System32" which is in %PATH% by default). I wanted to take things further and replicate this behavior on Win (and submit a patch), but as it turns out, [MSDN]: GetProcAddress function only "sees" exported symbols, so unless someone declares the functions in the main executable as __declspec(dllexport) (why on Earth the regular person would do that?), the main program is loadable but pretty much unusable
  3. Use [Python]: With Statement Context Managers. Either:

    • Create one:

      class Swallow:  # Dummy example
          def __enter__(self):
              print("Entering...")
      
          def __exit__(self, exc_type, exc_value, exc_traceback):
              print("Exiting:", exc_type, exc_value, exc_traceback)
              return True
      
      • And its usage - I'll replicate the isfile behavior (note that this is just for demonstrating purposes, do not attempt to write such code for production):

        import os
        import stat
        
        
        def isfile2(path):
            result = False
            with Swallow():
                result = stat.S_ISREG(os.stat(path).st_mode)
            return result
        
    • Use [Python]: contextlib.suppress(*exceptions) - which was specifically designed for selectively suppressing exceptions


    But, they seem to be wrappers over try/except/else/finally blocks, as [Python]: The with statement states:

    This allows common try...except...finally usage patterns to be encapsulated for convenient reuse.

  4. Use filesystem traversal functions (and search the results for matching item(s))


    Since these iterate over folders, (in most of the cases) they are inefficient for our problem (there are exceptions, like non wildcarded globbing - as @ShadowRanger pointed out), so I'm not going to insist on them. Not to mention that in some cases, filename processing might be required.

  5. Install some 3rd Party module with filesystem capabilities

    Most likely, will rely on one of the ways above (maybe with slight customizations).
    One example would be (again, Win specific) [SourceForge]: Python for Windows Extensions (pywin32), which is a Python wrapper over WINAPIs.

    But, since this is more like a workaround (gainarie), I'm stopping here.

share|improve this answer
    
Can you elaborate on this statement? "Although it's not a good practice, I'm using os.F_OK in the call, but that's just for clarity (its value is 0)" – sk8asd123 Nov 19 '17 at 1:46
2  
@sk8asd123: Kind of hard to doo it in a comment: generally, it's best to use constants with functions that they come together with. That applies when working with multiple modules that define the same constant, because some might not be up to date, and it's best for the functions and constants to be in sync. When working with ctypes (calling the functions directly) I should have defined the constant (from MSDN), or not use a constant at all. It's just a guideline that I use, in 99.9% it probably makes no difference (functionally). – CristiFati Nov 19 '17 at 23:54
1  
@CristiFati: As of 3.6, glob.iglob (and glob.glob as well) are based on os.scandir, so it's lazy now; to get the first hit in a directory of 10M files, you only scan until you reach the first hit. And even pre-3.6, if you use glob methods w/o any wildcards, the function is smart: It knows you can only have one hit, so it simplifies the globbing to just os.path.isdir or os.path.lexists (depending on whether path ends in /). – ShadowRanger Nov 29 '17 at 18:29
1  
That second part of my comment (non-wildcarded globbing doesn't actually iterate the folder, and never has) does mean it's a perfectly efficient solution to the problem (slower than directly calling os.path.isdir or os.path.lexist since it's a bunch of Python level function calls and string operations before it decides the efficient path is viable, but no additional system call or I/O work, which is orders of magnitude slower). – ShadowRanger Nov 29 '17 at 18:38
    
Thank you @ShadowRanger for your input. I'll surely check it out. – CristiFati Nov 30 '17 at 17:40

Date:2017-12-04

Every possible solution has been listed in other answers.

An intuitive and arguable way to check if a file exists is the following:

import os
os.path.isfile('~/file.md')    # Returns True if exists, else False
additionaly check a dir
os.path.isdir('~/folder') # Returns True if the folder exists, else False
check either a dir or a file
os.path.exists('~/file')

I made an exhaustive cheatsheet for your reference:

#os.path methods in exhaustive cheatsheet
{'definition': ['dirname',
               'basename',
               'abspath',
               'relpath',
               'commonpath',
               'normpath',
               'realpath'],
'operation': ['split', 'splitdrive', 'splitext',
               'join', 'normcase'],
'compare': ['samefile', 'sameopenfile', 'samestat'],
'condition': ['isdir',
              'isfile',
              'exists',
              'lexists'
              'islink',
              'isabs',
              'ismount',],
 'expand': ['expanduser',
            'expandvars'],
 'stat': ['getatime', 'getctime', 'getmtime',
          'getsize']}
share|improve this answer
3  
you have an error, it is os.path.exists not os.path.exist you are missing an s – Oren Dec 13 '17 at 10:35

Python 3.4+ has an object-oriented path module: pathlib. Using this new module, you can check whether a file exists like this:

import pathlib
p = pathlib.Path('path/to/file')
if p.is_file():  # or p.is_dir() to see if it is a directory
    # do stuff

You can (and usually should) still use a try/except block when opening files:

try:
    with p.open() as f:
        # do awesome stuff
except OSError:
    print('Well darn.')

The pathlib module has lots of cool stuff in it: convenient globbing, checking file's owner, easier path joining, etc. It's worth checking out. If you're on an older Python (version 2.6 or later), you can still install pathlib with pip:

# installs pathlib2 on older Python versions
# the original third-party module, pathlib, is no longer maintained.
pip install pathlib2

Then import it as follows:

# Older Python versions
import pathlib2 as pathlib
share|improve this answer
1  
pathlib is no longer maintained. Install pathlib2 rather: pip install pathlib – Charitoo Aug 15 '17 at 1:10

In this case you can check file name exist in listdir or not. if not the simply file not exist.

import os
filename = 'D:\\Python\\Python27\\prz\\passwords\\alpa.txt'
li = filename.split('\\')
st = ''
for i in range(0,len(li)-1):
    st = st + li[i] + '\\'
dirlist = os.listdir(st)
if(li[len(li)-1] in dirlist):
    fp = open(filename,'r')
else:
    print "FILE NOT FOUND"

This works perfect.

share|improve this answer

If you want to do that in Bash it would be:

if [ -e "$FILE" ]; then
    prog "$FILE"
fi

Which I sometimes do when using Python to do more complicated manipulation of a list of names (as I sometimes need to use Python for), the try open(file): except: method isn't really what's wanted, as it is not the Python process that is intended to open the file.

In one case, the purpose is to filter a list of names according to whether they exist at present (and there are no processes likely to delete the file, nor security issues since this is on my Raspberry Pi which has no sensitive files on its SD card).

I'm wondering whether a 'Simple Patterns' site would be a good idea? So that, for example, you could illustrate both methods with links between them and links to discussions as to when to use which pattern.

share|improve this answer

If the reason you're checking is so you can do something like if file_exists: open_it(), it's safer to use a try around the attempt to open it. Checking and then opening risks the file being deleted or moved or something between when you check and when you try to open it.

If you're not planning to open the file immediately, you can use os.path.isfile

Return True if path is an existing regular file. This follows symbolic links, so both islink() and isfile() can be true for the same path.

import os.path
os.path.isfile(fname) 

if you need to be sure it's a file.

Starting with Python 3.4, the pathlib module offers an object-oriented approach (backported to pathlib2 in Python 2.7):

from pathlib import Path

my_file = Path("/path/to/file")
if my_file.is_file():
    # file exists

To check a directory, do:

if my_file.is_dir():
    # directory exists

To check whether a Path object exists independently of whether is it a file or directory, use exists():

if my_file.exists():
    # path exists

You can also use resolve() in a try block:

try:
    my_abs_path = my_file.resolve():
except FileNotFoundError:
    # doesn't exist
else:
    # exists
share|improve this answer
5  
pathlib is also backported to 2.7. – TankorSmash Jan 20 '17 at 18:59
9  
The official backport is pathlib2, pathlib module isn't maintained anymore. – Laurent LAPORTE Feb 27 '17 at 21:45
1  
I totally agree that there is little reason to simply check for presence of a file unless the mere presence of it is a signal all by itself. In which case it would be better to have a CSV file where you write a value indicating the signal - and then can have more than one signal conveyed via a single file. – SDsolar Oct 12 '17 at 6:25
1  
Good point with the possibility of the file being changed after the check! – Charles Oct 18 '17 at 20:01
2  
There may be times when a try/catch is warranted, but I don't think that is the general rule. You want your program to crash when a critical exception like that occurs. All of your other resources should be handled by context managers, so they should be able to handle themselves in the event of an uncaught exception. – Multihunter Oct 20 '17 at 4:16

if you imported numpy already for other purposes then no need to import other libs like pathlib or os or paths etc. import numpy as np np.DataSource().exists("path/to/your/file") will return true or false based on its existence.

share|improve this answer

use this optimized code:-

from os import path def ex(file):

return path.isfile(str(file))

if ex('C:\\Users\\noredine\\Desktop\\sc\\AppendPayLoad.cpp'):
print 'bingo found'
else:
print 'not found'
share|improve this answer

How do I check whether a file exists, using Python, without using a try statement?

In Python 3.4 and on, use the new Path object in pathlib.

from pathlib import Path
import tempfile

>>> root = Path('/')
>>> root.is_file()
False
>>> root.exists()
True

So let's get a file that we know is a file:

>>> file = tempfile.NamedTemporaryFile()
>>> filepathobj = Path(file.name)
>>> filepathobj.is_file()
True
>>> filepathobj.exists()
True

By default, NamedTemporaryFile deletes the file when closed (and will automatically close when no more references exist to it).

>>> del file
>>> filepathobj.exists()
False
>>> filepathobj.is_file()
False

If you dig into the implementation, though, you'll see that is_file uses try:

def is_file(self):
    """
    Whether this path is a regular file (also True for symlinks pointing
    to regular files).
    """
    try:
        return S_ISREG(self.stat().st_mode)
    except OSError as e:
        if e.errno not in (ENOENT, ENOTDIR):
            raise
        # Path doesn't exist or is a broken symlink
        # (see https://bitbucket.org/pitrou/pathlib/issue/12/)
        return False

Without a try statement:

suppress

Python 3.4 gives us the suppress context manager (previously the ignore context manager), which does semantically exactly the same thing in fewer lines, while also (at least superficially) meeting the original ask to avoid a try statement:

from contextlib import suppress

with suppress(OSError), open(path) as f:
    f.read()

Usage:

>>> with suppress(OSError), open('doesnotexist') as f:
...     f.read()
... 
>>>

For earlier Pythons, you could roll your own suppress, but without a try will be much more verbose than with. I do believe this actually is the only answer that doesn't use try at any level that can be applied to prior to Python 3.4 because it uses a context manager instead:

class suppress(object):
    def __init__(self, *exceptions):
        self.exceptions = exceptions
    def __enter__(self):
        return self
    def __exit__(self, exc_type, exc_value, traceback):
        if exc_type is not None:
            return issubclass(exc_type, self.exceptions)

Easier with a try:

from contextlib import contextmanager

@contextmanager
def suppress(*exceptions):
    try:
        yield
    except exceptions:
        pass

Other options that don't meet the ask for "without try":

isfile

import os
os.path.isfile(path)

from the docs:

os.path.isfile(path)

Return True if path is an existing regular file. This follows symbolic links, so both islink() and isfile() can be true for the same path.

But if you examine the source of this function, you'll see it actually does use a try statement:

# This follows symbolic links, so both islink() and isdir() can be true
# for the same path on systems that support symlinks
def isfile(path):
    """Test whether a path is a regular file"""
    try:
        st = os.stat(path)
    except os.error:
        return False
    return stat.S_ISREG(st.st_mode)
>>> OSError is os.error
True

All it's doing is using the given path to see if it can get stats on it, catching OSError and then checking if it's a file if it didn't raise the exception.

If you intend to do something with the file, I would suggest directly attempting it with a try-except to avoid a race condition:

try:
    with open(path) as f:
        f.read()
except OSError:
    pass

os.access

Available for Unix and Windows is os.access, but to use you must pass flags, and it does not differentiate between files and directories. This is more used to test if the real invoking user has access in an elevated privilege environment:

import os
os.access(path, os.F_OK)

It also suffers from the same race condition problems as isfile. From the docs:

Note: Using access() to check if a user is authorized to e.g. open a file before actually doing so using open() creates a security hole, because the user might exploit the short time interval between checking and opening the file to manipulate it. It’s preferable to use EAFP techniques. For example:

if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"

is better written as:

try:
    fp = open("myfile")
except IOError as e:
    if e.errno == errno.EACCES:
        return "some default data"
    # Not a permission error.
    raise
else:
    with fp:
        return fp.read()
share|improve this answer
import os
os.path.exists(path) # returns whether the path (dir or file) exists or not
os.path.isfile(path) # returns whether the file exists or not
share|improve this answer
67  
This answer is wrong. os.path.exists returns true for things that aren't files, such as directories. This gives false positives. See the other answers that recommend os.path.isfile. – Chris Johnson May 23 '14 at 15:51
1  
@WaIR that's not right. os.path.exists('fred') also returns True if (for example) there's a directory (not file) named 'fred'. This answer does not indicate if a file of the given file name exists, only that a file system object of some type exists. Does not satisfy the OP question. – Chris Johnson Dec 22 '16 at 21:58
import os.path

if os.path.isfile(filepath):
share|improve this answer

In Python 3.4 the language provides a new module to manage files:

import pathlib
path = pathlib.Path('path/to/file')
if path.is_file(): # If you want to check a directory: path.is_dir()
    # If it is true, return true on your code.
share|improve this answer
5  
How is this any different from Cody Piersall's answer? – cpburnz Jun 30 '16 at 22:06

In 2016 the best way is still using os.path.isfile:

>>> os.path.isfile('/path/to/some/file.txt')

Or in Python 3 you can use pathlib:

import pathlib
path = pathlib.Path('/path/to/some/file.txt')
if path.is_file():
    ...
share|improve this answer
3  
May I ask: What's the advantage of using the module 'pathlib' instead of the module 'os' in python3 for this checking? – Joko Feb 25 '16 at 8:55
3  
pathlib is python's OOP solution for paths. You can do a lot more with it. If you just need to check existance, the advantage is not so big. – KaiBuxe Feb 25 '16 at 10:44

I'm the author of a package that's been around for about 10 years, and it has a function that addresses this question directly. Basically, if you are on a non-Windows system, it uses Popen to access find. However, if you are on Windows, it replicates find with an efficient filesystem walker.

The code itself does not use a try block… except in determining the operating system and thus steering you to the "Unix"-style find or the hand-buillt find. Timing tests showed that the try was faster in determining the OS, so I did use one there (but nowhere else).

>>> import pox
>>> pox.find('*python*', type='file', root=pox.homedir(), recurse=False)
['/Users/mmckerns/.python']

And the doc…

>>> print pox.find.__doc__
find(patterns[,root,recurse,type]); Get path to a file or directory

    patterns: name or partial name string of items to search for
    root: path string of top-level directory to search
    recurse: if True, recurse down from root directory
    type: item filter; one of {None, file, dir, link, socket, block, char}
    verbose: if True, be a little verbose about the search

    On some OS, recursion can be specified by recursion depth (an integer).
    patterns can be specified with basic pattern matching. Additionally,
    multiple patterns can be specified by splitting patterns with a ';'
    For example:
        >>> find('pox*', root='..')
        ['/Users/foo/pox/pox', '/Users/foo/pox/scripts/pox_launcher.py']

        >>> find('*shutils*;*init*')
        ['/Users/foo/pox/pox/shutils.py', '/Users/foo/pox/pox/__init__.py']

>>>

The implementation, if you care to look, is here: https://github.com/uqfoundation/pox/blob/89f90fb308f285ca7a62eabe2c38acb87e89dad9/pox/shutils.py#L190

share|improve this answer

How do I check whether a file exists, without using the try statement?

In 2016, this is still arguably the easiest way to check if both a file exists and if it is a file:

import os
os.path.isfile('./file.txt')    # Returns True if exists, else False

isfile is actually just a helper method that internally uses os.stat and stat.S_ISREG(mode) underneath. This os.stat is a lower-level method that will provide you with detailed information about files, directories, sockets, buffers, and more. More about os.stat here

Note: However, this approach will not lock the file in any way and therefore your code can become vulnerable to "time of check to time of use" (TOCTTOU) bugs.

So raising exceptions is considered to be an acceptable, and Pythonic, approach for flow control in your program. And one should consider handling missing files with IOErrors, rather than if statements (just an advice).

share|improve this answer

Although I always recommend using try and except statements, here are a few possibilities for you (my personal favourite is using os.access):

  1. Try opening the file:

    Opening the file will always verify the existence of the file. You can make a function just like so:

    def File_Existence(filepath):
        f = open(filepath)
        return True
    

    If it's False, it will stop execution with an unhanded IOError or OSError in later versions of Python. To catch the exception, you have to use a try except clause. Of course, you can always use a try except` statement like so (thanks to hsandt for making me think):

    def File_Existence(filepath):
        try:
            f = open(filepath)
        except IOError, OSError: # Note OSError is for later versions of Python
            return False
    
        return True
    
  2. Use os.path.exists(path):

    This will check the existence of what you specify. However, it checks for files and directories so beware about how you use it.

    import os.path
    >>> os.path.exists("this/is/a/directory")
    True
    >>> os.path.exists("this/is/a/file.txt")
    True
    >>> os.path.exists("not/a/directory")
    False
    
  3. Use os.access(path, mode):

    This will check whether you have access to the file. It will check for permissions. Based on the os.py documentation, typing in os.F_OK, it will check the existence of the path. However, using this will create a security hole, as someone can attack your file using the time between checking the permissions and opening the file. You should instead go directly to opening the file instead of checking its permissions. (EAFP vs LBYP). If you're not going to open the file afterwards, and only checking its existence, then you can use this.

    Anyway, here:

    >>> import os
    >>> os.access("/is/a/file.txt", os.F_OK)
    True
    

I should also mention that there are two ways that you will not be able to verify the existence of a file. Either the issue will be permission denied or no such file or directory. If you catch an IOError, set the IOError as e (like my first option), and then type in print(e.args) so that you can hopefully determine your issue. I hope it helps! :)

share|improve this answer

You can use the "OS" library of Python:

>>> import os
>>> os.path.exists("C:\\Users\\####\\Desktop\\test.txt") 
True
>>> os.path.exists("C:\\Users\\####\\Desktop\\test.tx")
False
share|improve this answer
1  
This answer is wrong. os.path.exists returns true for things that aren't files, such as directories. This gives false positives. See the other answers that recommend os.path.isfile. – Chris Johnson Aug 1 '15 at 13:55
    
@Chris Johnson , os.path.exists() function checks whether a path exists in system. PATH may be a DIRECTORY or FILE. It will work fine on both the cases. Please try with some example – Pradip Das Aug 2 '15 at 14:51
1  
You didn't answer the original question, which was about files. – Chris Johnson Aug 3 '15 at 12:41
    
6 months later, answer is still wrong. – Chris Johnson Feb 17 '16 at 18:55
    
So, this answer works. Great. Iff the path isn't that of a file. Is that what the question was about? No. – Debosmit Ray Apr 14 '16 at 23:33

You can use the following open method to check if a file exists + readable:

open(inputFile, 'r')
share|improve this answer
    
Just make sure you remember to close the file afterwards! – Zizouz212 Feb 5 '15 at 3:27

You can write Brian's suggestion without the try:.

from contextlib import suppress

with suppress(IOError), open('filename'):
    process()

suppress is part of Python 3.4. In older releases you can quickly write your own suppress:

from contextlib import contextmanager

@contextmanager
def suppress(*exceptions):
    try:
        yield
    except exceptions:
        pass
share|improve this answer

You can simply use the tempfile module to know whether a file exists or not:

import tempfile

tempfile._exists('filename') # Returns True or False
share|improve this answer
10  
-1 no good reason to use a _protected method when the same functionality is in os.path – wim Apr 9 '13 at 2:53
    
You can use this if you are not sure about whether its a file or directory. – akashdeep Apr 9 '13 at 8:32
2  
Not only that, _protected methods aren't meant to be used; They are a non-public part of the API. Documentation goes crazy about that. – Zizouz212 Feb 15 '15 at 22:09
    
It is recommended to use os.path functions – albert Aug 28 '17 at 10:17

You could try this (safer):

try:
    # http://effbot.org/zone/python-with-statement.htm
    # 'with' is safer to open a file
    with open('whatever.txt') as fh:
        # Do something with 'fh'
except IOError as e:
    print("({})".format(e))

The ouput would be:

([Errno 2] No such file or directory: 'whatever.txt')

Then, depending on the result, your program can just keep running from there or you can code to stop it if you want.

share|improve this answer
13  
The original question asked for a solution that does not use try – rrs Apr 23 '14 at 13:10
4  
This answer misses the point of the OP. Checking is a file exists is not the same as checking if you can open it. There will be cases where a file does exist but for a variety of reasons, you can't open it. – Chris Johnson Feb 17 '16 at 18:52
import os
#Your path here e.g. "C:\Program Files\text.txt"
#For access purposes: "C:\\Program Files\\text.txt"
if os.path.exists("C:\..."):   
    print "File found!"
else:
    print "File not found!"

Importing os makes it easier to navigate and perform standard actions with your operating system.

For reference also see How to check whether a file exists using Python?

If you need high-level operations, use shutil.

share|improve this answer
9  
This answer is wrong. os.path.exists returns true for things that aren't files, such as directories. This gives false positives. See the other answers that recommend os.path.isfile. – Chris Johnson Aug 1 '15 at 13:56
    
>>> if os.path.exists("C:\\GnuWin32\\bin\\parser_main.c"): print(True) else: print(False)....Returns true for the parser_main.c which is a file! Thanks for pointing that out though. :) – Bishop May 16 '17 at 16:32
1  
I will rephrase. os.path.exists returns True for files and ALSO for non-files. So if you need to check specifically for file existence, this function is over-broad. – Chris Johnson May 16 '17 at 18:05
    
I see. I even compared some other functions I found. You're on point. I appreciate your response on the matter. – Bishop May 17 '17 at 12:59

I would try something along the lines of the following using the call to import os:

import os
fname = "foo.txt"
if os.path.isfile(fname):
    print("file does exist at this time")
else:
    print("no such file")
share|improve this answer
    
How is this different from @rslite answer? – jorgeh May 15 '17 at 18:08
    
same conclusion I guess? – Oliver Jul 14 '17 at 23:04

Adding one more slight variation which isn't exactly reflected in the other answers.

This will handle the case of the file_path being None or empty string.

def file_exists(file_path):
    if not file_path:
        return False
    elif not os.path.isfile(file_path):
        return False
    else:
        return True

Adding a variant based on suggestion from Shahbaz

def file_exists(file_path):
    if not file_path:
        return False
    else:
        return os.path.isfile(file_path)

Adding a variant based on suggestion from Peter Wood

def file_exists(file_path):
    return file_path and os.path.isfile(file_path):
share|improve this answer
2  
if (x) return true; else return false; is really just return x. Your last four lines can become return os.path.isfile(file_path). While we're at it, the whole function can be simplified as return file_path and os.path.isfile(file_path). – Shahbaz Jan 4 '17 at 22:50
    
You have to be careful with return x in the case of if (x). Python will consider an empty string False in which case we would be returning an empty string instead of a bool. The purpose of this function is to always return bool. – Marcel Wilson Jan 5 '17 at 17:08
1  
True. In this case however, x is os.path.isfile(..) so it's already bool. – Shahbaz Jan 5 '17 at 17:10
    
os.path.isfile(None) raises an exception which is why I added the if check. I could probably just wrap it in a try/except instead but I felt it was more explicit this way. – Marcel Wilson Jan 5 '17 at 17:13
2  
return file_path and os.path.isfile(file_path) – Peter Wood Apr 6 '17 at 10:35

You have the os.path.exists function:

import os.path
os.path.exists(file_path)

This returns True for both files and directories but you can instead use os.path.isfile to test if it's a file specifically. It follows symlinks.

share|improve this answer

Unlike isfile(), exists() will return True for directories.
So depending on if you want only plain files or also directories, you'll use isfile() or exists(). Here is a simple REPL output.

>>> print os.path.isfile("/etc/password.txt")
True
>>> print os.path.isfile("/etc")
False
>>> print os.path.isfile("/does/not/exist")
False
>>> print os.path.exists("/etc/password.txt")
True
>>> print os.path.exists("/etc")
True
>>> print os.path.exists("/does/not/exist")
False
share|improve this answer

Testing for files and folders with os.path.isfile(), os.path.isdir() and os.path.exists()

Assuming that the "path" is a valid path, this table shows what is returned by each function for files and folders:

enter image description here

You can also test if a file is a certain type of file using os.path.splitext() to get the extension (if you don't already know it)

>>> import os
>>> path = "path to a word document"
>>> os.path.isfile(path)
True
>>> os.path.splitext(path)[1] == ".docx" # test if the extension is .docx
True
share|improve this answer

You can use os.listdir to check if a file is in a certain directory.

import os
if 'file.ext' in os.listdir('dirpath'):
    #code
share|improve this answer
1  
won't work in windows since filesystem isn't case sensitive. And very uneffective because it scans the whole directory. – Jean-François Fabre Jan 7 '17 at 12:24

Additionally, os.access():

if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()

Being R_OK, W_OK, and X_OK the flags to test for permissions (doc).

share|improve this answer

protected by NullPoiиteя Jun 10 '13 at 5:13

Thank you for your interest in this question. Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).

Would you like to answer one of these unanswered questions instead?

Not the answer you're looking for? Browse other questions tagged or ask your own question.