Python os.path Library and Using exist, isdir, isfile Examples
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.
Before starting examples we need to
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.
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 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
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
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.
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.