How to verify 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 the symbolic links, such that islink() and isfile() can be true for the same route.

import os.path

If you need to be sure that it is a.

Original answer:

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

import os.path as path

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

The difference with isfile() is that os.path.exists() 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 it is necessary to install 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