gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 05:59:28 27 4
gpt4 key购买 nike

我不太确定这里发生了什么。基于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。

关于python - 为什么文件可写但 os.access( file, os.W_OK ) 返回 false?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25908743/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com