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')
>>> os.path.isdir('/users/john/images')
>>> os.path.isfile('/users/john/images')

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/')


Links Site
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
Python: Check if a File or Directory Exists stackabuse