This tutorial includes:

1. Check if file exists

For example, To test how isfile() and exists() functions work. Create a TestFile.py file using following content and execute it python.

isfile() – function check if given input file exists and is a file not directory. exists() – function check if given input file/directory exists.

See the below examples:

Python >= 3.4 users can use object oriented approach to check if file exist or not. we need to import Path from the pathlib module.

2. Check if file is readable

You can also check if the file exists and is readable for the current users in Python.

Use os.path.islink to find if any file is a link file.

3. Create a directory if not exists

Use os.path.exists to check if any directory exists or not and use os.makedirs to create a directory. Below example will create a directory /tmp/newdir if not exists.