How to check if a file exists in python ?

How to check if a file exists in python ?

Daidalos April 15, 2020


Example of how to check if a file exists in python:

Using the os function isfile()

To check if a file (called for example "photo_001.png") exists, a solution in python is to use the functionisfile:

>>> import os
>>> os.path.isfile('photo_001.png')

that returns a boolean (True or False) is the file 'photo_001.png' exists or not. =

To test if the file is available with the path /users/john/photo_001.png:

>>> import os
>>> os.path.isdir('/users/john/photo_001.png')

Function os.path.exists()

Note 1: the function os.path.exists() is used ti check if a path exists but it can be a file or a directory:

>>> import os
>>> os.path.exists('/users/john/images')
True
>>> os.path.isdir('/users/john/images')
True
>>> os.path.isfile('/users/john/images')
False

Note 2: to get a list of files and directories available under '/users/john/' a solution is to use os.listdir():

>>> os.path.listdir('/users/john/')

References

Links Site
isfile docs.python.org
isdir docs.python.org
how to check if a file is a directory or regular file in python? [duplicate] stackoverflow
How do I list all files of a directory? stackoverflow
Getting file size in Python? [duplicate] stackoverflow
Python Check If File or Directory Exists guru99.com
Python: Check if a File or Directory Exists stackabuse