How to check that a file exists in Python?


Using Python, how do I check if a file exists, without using the try statement.

original question :


You can use os.path.isfile :

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

import os.path

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

original answer:

You can use the method indicated by @campussano using os.path.exists() :

import os.path as path

if path.exists(file):
   # código

The difference with isfile() is that os.path.exists() will return True for files and folders

You can use the method presented by @toledano using the unipath module which is not included in Python and needs to be installed previously:

$ pip install unipath


from unipath import Path
f = Path('ejemplo.txt')

In general, the use of unipath.Path is simpler than os.path , especially when creating routes.

# con os.path
os.path.join(A, B)

# con unipath.Path
Path(A, B)
Scroll to Top