In this article we will discuss techniques in python to check if a file , link or directory exists or not.

Check if a path exists

Python’s os module provides a function to check if a given path exists or not i.e.

It will True if the path exists else it will give False. Parameter path can be a relative or an absolute path.
For example,

Some Points to remember:

  •  In case path is of a symbolic link and link is broken i.e, file it points too doesnot exists, then it will return False.
  • It can also return False if we don’t have permission to read the entity at given path.

With os.path.exists(path) we can make sure that given path exists or not but we can not make sure if it’s a file or directory or link.

Check if a file exists

Python’s os module provides a function to check if a given file exists or not i.e.

It will return True if given path points to a file and that exists.

Why we need to check if a file exists ?

Suppose we want to open a file but if that file doesn’t exists then it will throw error FileNotFoundError at runtime i.e.

FileNotFoundError: [Errno 2] No such file or directory: ‘/home/varun/temp/sample1.csv’

To avoid this kind of error, we should first check if file exists or not. Let’s see how to do that i.e.

Check if a Directory exists

Python’s os module provides a function to check if a given directory exists or not i.e.

It will return True if given path points to a directory and that exists.

Example,

Both os.path.isdir() & os.path.isfile() returns True in case of symbolic links too (not broken). But we have another API to check separately if given path is a link or not.

Check if given path is a link

On the similar lines, Python’s os module provides a function to check if a given path is a link that exists i.e.

It will return True if given path points to a link, even if that is broken.

To check if given path is a link and that is not broken i.e. file/dir it points to exists, we need to use exists() along with islink() i.e.

Complete example is as follows,

Output:

 

Click Here to Subscribe for more Articles / Tutorials like this.