Skip to main content
 首页 » 编程设计

python之为什么文件可写但 os.access( file, os.W_OK ) 返回 false

2025年05月04日11thcjp

我不太确定这里发生了什么。基于python上的解释

> os.W_OK: 包含在 access() 的模式参数中的值以测试路径的可写性。

我想这个检查应该返回 True,即使文件不存在,但它的路径有效并且我有写这个文件的权限。

但这是当我尝试检查文件路径是否可写时发生的情况。

import os, subprocess 
pwd = os.getcwd(); 
temp_file_to_write = os.path.join( pwd, "temp_file" ); 
# use os.access to check  
say = ""; 
if ( os.access( temp_file_to_write, os.W_OK ) ) : 
    say = "writeable"; 
else : 
    say = "NOT writeable"; 
 
print "L10", temp_file_to_write, "is", say 
# use try/except 
try : 
    with open( temp_file_to_write, "w" ) as F : 
        F.write( "L14 I am a temp file which is said " + say + "\n" ); 
    print "L15", temp_file_to_write, "is written"; 
    print subprocess.check_output( ['cat', temp_file_to_write ] ); 
except Exception, e: 
    print "L18", temp_file_to_write, "is NOT writeable"; 

它产生以下结果

L10 /home/rex/python_code/sandbox/temp_file is NOT writeable 
L15 /home/rex/python_code/sandbox/temp_file is written 
L14 I am a temp file which is said NOT writeable 

有人知道为什么吗?如果我对 os.W_OK 的理解是错误的,你能告诉我在 python 中一起检查以下两件事的正确方法 1) 文件路径是否有效; 2) 我是否有写权限。

请您参考如下方法:

您是否可以创建新文件取决于目录 拥有的权限,而不是新的(尚不存在的)文件。

文件创建(存在)后,如果您可以修改其内容,access(W_OK) 可能会返回 true。