Python os.path Library and Using exist, isdir, isfile Examples – POFTUT

Python os.path Library and Using exist, isdir, isfile Examples


Python provides os.path module in order to use some file and directory related functions. We can use os.pathin order to check whether a file or directory exists, given path is file or directory, the access time of the directory and path etc.

Import os.path

Before starting examples we need to import os.path module which provides functionalities examined below.

import os.path

Check Given File or Directory Exist

If we will write or create a file we may need to check whether destination file or directory exists or we want to read a file but we should check before creating exceptions. We can use existsfunctions for this situation. In this example we will check wheter /home/ismail directory exists. We can also provide a file name to check the existence.

os.path.exists('/home/ismail')
Check Given File or Directory Exist
Check Given File or Directory Exist

As we can the given directory exists where the exists method returns Boolean True. If the directory do not exists it will return false like below.

 os.path.exists('/home/no')
Check Given File or Directory Exist
Check Given File or Directory Exist

Check Given Path Is Directory

After checking the directory or file existence we may want to check whether given path is a directory or a file. We will use isdir function in order to return Boolean value. If given path is directory isdir function will return True if not False.

os.path.isdir('/home/ismail')
Check Given Path Is Directory
Check Given Path Is Directory

Check Given Path Is File

We can check given path is it is a file. As we know there are different type of files and links. This function will also check if given path is a link where points another path. If given path is file isfile function will return True.

 os.path.isfile('/home/ismail')

Get Given File or Directory Access Time

We can also get access time of given file or directory. We will use getatime which is the short form of get access time . This will return access time as seconds in Unix format.

 os.path.getatime('/home/ismail')
Get Given File or Directory Access Time
Get Given File or Directory Access Time

Get Given File or Directory Modification Time

Another useful function is modification time. We can use  getmtime function which is very similar to the access time. The time is returned as Unix time stamp as seconds.

 os.path.getmtime('/home/ismail')
Get Given File or Directory Modification Time
Get Given File or Directory Modification Time

LEARN MORE  Linux stat Command Tutorial With Examples

Leave a Comment