We now have a youtube channel. Subscribe!

Python os.access() Method with example



Hello dear readers! Welcome back to another section of our tutorial on Python. In this tutorial guide, we are going to be studying about the Os access() method.

Python os access() method uses the real uid/gid to test for access. Most operations uses the effective uid/gid, therefore this routine can be used in a suid/sgid program to test if the invoking user have got the specified access to path. It returns True if access is allowed, otherwise False.

Syntax

The following below is the syntax for Python Os access() method -

os.access(path,  mode);


Parameter Details

  • path - Path which would be tested for existence or any access.
  • mode - This should be F_OK to test the existence of path, it can as well be the inclusive OR of one or more R_OK, W_OK and X_OK for testing of permission.
    • os.F_OK - Value to be passed as the mode parameter of access() to test the existence of path.
    • os.R_OK - The value to be included in the mode parameter of access() to test the readability of path.
    • os.W_OK - The value to be included in the mode parameter of access() to test the writability of path.
    • os.X_OK - The value to be included in the mode parameter of access() to check if path can be executed.

Return Value

This method returns True if access is allowed, otherwise False.

Example

The following below is a simple example -

#!/usr/bin/python

import os, sys

# Assuming /tmp/foo.txt exists and has read/write permissions.

ret = os.access("/tmp/foo.txt", os.F_OK)
print "F_OK - return value %s"% ret

ret = os.access("/tmp/foo.txt", os.R_OK)
print "R_OK - return value %s"% ret

ret = os.access("/tmp/foo.txt", os.W_OK)
print "W_OK - return value %s"% ret

ret = os.access("/tmp/foo.txt", os.X_OK)
print "X_OK - return value %s"% ret

Output
When the above code is executed, it will produce the following result -

F_OK - return value True
R_OK - return value True
W_OK - return value True
X_OK - return value False


Alright guys! This is where we are rounding up for this tutorial post. In our next tutorial, we are going to be studying about the Python OS chdir() Method.

Feel free to ask your questions where necessary and i will attend to them as soon as possible. If this tutorial was helpful to you, you can use the share button to share this tutorial.

Follow us on our various social media platforms to stay updated with our latest tutorials. You can also subscribe to our newsletter in order to get our tutorials delivered directly to your emails.

Thanks for reading and bye for now.

Post a Comment

Hello dear readers! Please kindly try your best to make sure your comments comply with our comment policy guidelines. You can visit our comment policy page to view these guidelines which are clearly stated. Thank you.
© 2023 ‧ WebDesignTutorialz. All rights reserved. Developed by Jago Desain