How To Use Python Os.path Module To Operate Directory

The python os.path module provides some methods to operate a directory. This module provides the following methods for you to use. This article will show you how to use them with examples.

1. Python os.path Module Methods.

    1. exists(): The exists function determines whether the directory exists or not.
    2. getctime(): Get the creation time of the directory.
    3. getmtime(): Get the directory last modified time.
    4. getatime(): Get the directory last access time.
    5. getsize(): Get the size of the specified file.

2. Python os.path Module Examples.

import os

import time

if __name__ == '__main__':
    
    # Get absolute path.
    abs_path = os.path.abspath(".")
    print(abs_path)
    
    # Get common prefix for different path value.
    path1 = '/usr/lib'
    path2 = '/usr/local/lib'
    common_prefix = os.path.commonprefix([path1, path2])
    print(common_prefix)
    
    # Get common path for different path value.
    common_path = os.path.commonpath([path1, path2])
    print(common_path)
    
    # Get file directory.
    current_dir = os.path.dirname('/usr/local/etc')
    print(current_dir)
    
    # Check if the specified directory exist or not.
    exist = os.path.exists('/usr/local/etc')
    print(exist)
    
    # Get the file last access time.
    a_time = os.path.getatime('os_path_module_example.py')
    print(time.ctime(a_time))
    
    # Get the file last modify time.
    m_time = os.path.getmtime('os_path_module_example.py')
    print(time.ctime(m_time))
    
    # Get the file creation time.
    c_time = os.path.getctime('os_path_module_example.py')
    print(time.ctime(c_time))
    
    # Get the file size.
    f_size = os.path.getsize('os_path_module_example.py')
    print(f_size)
    
    # Check whether it is a file or not.
    is_file = os.path.isfile('os_path_module_example.py')
    print(is_file)
    
    # Check whether it is a directory or not.
    is_dir = os.path.isdir('os_path_module_example.py')
    print(is_dir)
    
    # Check whether the two files are same file.
    file1 = 'os_path_module_example.py'
    file2 = './os_path_module_example.py'
    same_file = os.path.samefile(file1, file2)
    print(same_file)

Below is the above python code output.

/Users/songzhao/Documents/WorkSpace/dev2qa.com-example-code/PythonExampleProject/com/dev2qa/example/file
/usr/l
/usr
/usr/local
True
Wed Feb  3 05:07:59 2021
Wed Feb  3 05:07:58 2021
Wed Feb  3 05:07:58 2021
1684
True
False
True

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.