Python | os。access()方法

操作系统模块 在Python中,提供了与操作系统交互的函数。OS属于Python的标准实用程序模块。该模块提供了一种使用操作系统相关功能的便携方式。

null

os.access() 方法使用真实的uid/gid来测试对路径的访问。大多数操作都使用有效的uid/gid,因此,可以在suid/sgid环境中使用此例程来测试调用用户是否具有指定的路径访问权限。

语法:

os.access(path, mode)

参数:

路径: 要测试访问或存在的路径 模式: 应该是F_OK以测试路径的存在,或者可以是R_OK、W_OK和X_OK中的一个或多个的包含或,以测试权限。

以下值可以作为access()的模式参数传递,以测试以下内容:

  • 操作系统。好的: 测试路径的存在性。
  • 操作系统。好的: 测试路径的可读性。
  • 操作系统。好的: 测试路径的可写性。
  • 操作系统。好的: 检查路径是否可以执行。

    返回: 如果允许访问,则返回True,否则返回False。

    代码#1: 了解access()方法

    # Python program tyring to access
    # file with different mode parameter
    # importing all necessary libraries
    import os
    import sys
    # Different mode parameters will
    # return True if access is allowed,
    # else returns False.
    # Assuming only read operation is allowed on file
    # Checking access with os.F_OK
    path1 = os.access( "gfg.txt" , os.F_OK)
    print ( "Exists the path:" , path1)
    # Checking access with os.R_OK
    path2 = os.access( "gfg.txt" , os.R_OK)
    print ( "Access to read the file:" , path2)
    # Checking access with os.W_OK
    path3 = os.access( "gfg.txt" , os.W_OK)
    print ( "Access to write the file:" , path3)
    # Checking access with os.X_OK
    path4 = os.access( "gfg.txt" , os.X_OK)
    print ( "Check if path can be executed:" , path4)

    
    

    输出:

    Exists the path: True
    Access to read the file: True
    Access to write the file: False
    Check if path can be executed: False

    代码#2: 验证访问权限后打开文件的代码

    # Python program to open a file
    # after validating the access
    # checking readability of the path
    if os.access( "gfg.txt" , os.R_OK):
    # open txt file as file
    with open ( "gfg.txt" ) as file :
    return file .read()
    # in case can't access the file
    return "Facing some issue"

    
    

    输出:

    Facing some issue
  • © 版权声明
    THE END
    喜欢就支持一下吧
    点赞8 分享