How to check that a file exists in Python?

Question:

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

original question :

Answer:

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
os.path.isfile(fname) 

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

Example:

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

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