How to check whether a file exists?

+3961 votes
asked Sep 17, 2008 by spence91

How to see if a file exists or not, without using the try statement?

29 Answers

+802 votes
answered Sep 17, 2008 by bortzmeyer

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
+202 votes
answered Sep 17, 2008 by yugal-jindle

Use os.path.isfile() with os.access():

import os
import os.path
PATH='./file.txt'
if os.path.isfile(PATH) and os.access(PATH, os.R_OK): print "File exists and is readable"
else: print "Either file is missing or is not readable"
+3598 votes
answered Sep 17, 2008 by rslite

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 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
+43 votes
answered Sep 17, 2008 by zizouz212

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 hsandtfor 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! :)

+1456 votes
answered Sep 17, 2008 by pierrebdr

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.

+107 votes
answered Nov 4, 2009 by cody-piersall

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
+54 votes
answered Jan 25, 2011 by kaibuxe

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(): ...
+417 votes
answered Jan 16, 2012 by paul
import os.path
if os.path.isfile(filepath):
+179 votes
answered Jun 27, 2013 by benefactual
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
+61 votes
answered Sep 25, 2013 by tom-fuller

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
Welcome to Q&A, where you can ask questions and receive answers from other members of the community.
Website Online Counter

...