[파이썬] os 파일 권한 확인: `os.access()`

In Python, the os.access() function can be utilized to check the permissions or access rights of a file. This function is part of the os module, which provides a way to interact with the operating system.

The os.access() function takes two parameters: the path of the file or directory, and the mode of access for which the permission needs to be checked. It returns True if the access is allowed, False otherwise.

Here is the syntax for using the os.access() function:

import os

path = '/path/to/file.txt'
mode = os.R_OK  # Read permission

if os.access(path, mode):
    print("Read access is allowed for the file.")
else:
    print("Read access is not allowed for the file.")

In the above example, we are checking if the file located at '/path/to/file.txt' has read access. We pass the os.R_OK constant as the mode, which represents the read permission. If the file has read access, it will print “Read access is allowed for the file.” Otherwise, it will print “Read access is not allowed for the file.”

Here are the different modes that can be passed to os.access():

You can combine multiple modes using the bitwise or (|) operator. For example, os.R_OK | os.W_OK checks if read and write access are allowed.

It’s important to note that the os.access() function only checks the permissions of the current user. It doesn’t take into account other factors such as ownership or group permissions.

So, the next time you need to verify the permissions of a file in your Python script, consider using the os.access() function for a straightforward solution.