Check whether a file or path exists

suggest change

Employ the EAFP coding style and try to open it.

import errno

try:
    with open(path) as f:
        # File exists
except IOError as e:
    # Raise the exception if it is not ENOENT (No such file or directory)
    if e.errno != errno.ENOENT:
        raise
    # No such file or directory

This will also avoid race-conditions if another process deleted the file between the check and when it is used. This race condition could happen in the following cases:

import os
os.path.isfile('/path/to/some/file.txt')
import pathlib
path = pathlib.Path('/path/to/some/file.txt')
if path.is_file():
    ...

To check whether a given path exists or not, you can follow the above EAFP procedure, or explicitly check the path:

import os
path = "/home/myFiles/directory1"

if os.path.exists(path):
    ## Do stuff

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Files, Folders, I/O:
* Check whether a file or path exists

Table Of Contents
2 Filter
3 List
7 Loops
15 Files, Folders, I/O
22 Reduce
27 Classes
31 Set
42 Tuple
45 Enum
62 Sockets
89 urllib
92 Idioms
104 Stack
105 Profiling
109 Logging
111 os module
118 Mixins
120 ArcPy
126 Arrays
132 2to3 tool
135 Unicode
138 Neo4j
140 Curses
141 Templates
145 heapq
146 tkinter
154 Audio
155 pyglet
157 ijson
160 Flask
161 Groupby
163 pygame
165 hashlib
166 Gzip
167 ctypes
185 pyaudio
186 shelve