使用 os.access()
和 os.R_OK
在这一步中,我们将使用 Python 中的 os.access()
函数来检查文件是否具有读取权限。os.access()
函数接受两个参数:文件路径和权限标志。我们将使用 os.R_OK
来检查读取权限。
首先,让我们在 ~/project
目录中创建一个名为 check_permissions.py
的新 Python 文件。打开 VS Code 编辑器,并将以下代码添加到文件中:
import os
file_path = "my_script.py"
## Check if the file exists
if not os.path.exists(file_path):
print(f"Error: The file '{file_path}' does not exist.")
else:
## Check if the file has read permissions
if os.access(file_path, os.R_OK):
print(f"The file '{file_path}' has read permissions.")
else:
print(f"The file '{file_path}' does not have read permissions.")
保存文件。这个脚本首先检查 my_script.py
文件是否存在。如果存在,它会使用 os.access()
和 os.R_OK
来检查文件是否具有读取权限。脚本会打印一条消息,指示文件是否具有读取权限。
现在,从终端运行脚本:
python check_permissions.py
你应该会看到以下输出:
The file 'my_script.py' has read permissions.
这是因为默认情况下,my_script.py
文件对所有者、用户组和其他用户都有读取权限。
现在,让我们修改 my_script.py
文件的权限,以移除除所有者之外的所有人的读取权限。我们可以在终端中使用 chmod
命令来完成此操作。
chmod 600 my_script.py
此命令将 my_script.py
的权限设置为仅所有者具有读取和写入权限(八进制表示为 600)。
现在,再次运行 check_permissions.py
脚本:
python check_permissions.py
你现在应该会看到以下输出:
The file 'my_script.py' does not have read permissions.
这是因为我们已经移除了用户组和其他用户的读取权限。os.access()
函数正确识别出运行脚本的用户(即 labex
)对该文件不再具有读取权限。
最后,让我们恢复 my_script.py
文件的原始权限:
chmod 644 my_script.py
此命令将 my_script.py
的权限设置为所有者具有读取和写入权限,用户组和其他用户具有只读权限(八进制表示为 644)。