我有这个代码:
import os
print(os.access("tst.txt", os.R_OK))
open("tst.txt", "rb")
# File Permissions:
# Owner: Trusted Installer
# Administrators and my user: deny all permissions
os.access
返回 True
但打开文件会引发 PermissionError 异常。
如果我在另一个文件(如 cmd.exe、notepad.exe、System32 目录本身或任何其他文件)上尝试此操作,它总是返回 True。
如果文件不存在,则返回 False。
SO: True
在任何现有文件上。即使没有写入权限。
我在 Internet 上找不到任何相关信息。
有人知道为什么会出现这个问题吗?
编辑: 当然我的脚本没有以管理员身份运行。
无论我测试读还是写访问。
最佳答案
看起来 os.access
不检查 Windows 上的用户权限,它只检查是否设置了只读标志。
Note that os.access doesn't check file security on Windows. W_OK just checks the read-only flag. Thus using try...except is really the only possibility if you're on Windows and aren't using the Windows security API .
来自 http://net-informations.com/python/file/exists.htm
在这种情况下,您可能必须在代码周围包装一个 try...except
关于python - os.access 返回 True,但文件不可写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66035948/