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

RSS
EMAIL
FACEBOOK
FACEBOOK
GOOGLE
GOOGLE
https://www.poftut.com/python-os-path-library-using-exist-isdir-isfile-examples/
PINTEREST
PINTEREST
INSTAGRAM

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.

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.

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.

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.

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.

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.

LEARN MORE  Linux stat Command Tutorial With Examples

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.

Get Given File or Directory Modification Time

Get Given File or Directory Modification Time

RSS
EMAIL
FACEBOOK
FACEBOOK
GOOGLE
GOOGLE
https://www.poftut.com/python-os-path-library-using-exist-isdir-isfile-examples/
PINTEREST
PINTEREST
INSTAGRAM

You may also like...

Leave a Reply

Your email address will not be published.

Enjoy this blog? Please spread the word :)