【发布时间】:2014-11-12 13:29:57
【问题描述】:
我不太确定这里发生了什么。基于python上的解释
> os.W_OK: access() 的 mode 参数中包含的值,用于测试路径的可写性。
我想这个检查应该返回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) 我是否有写权限。
【问题讨论】:
标签: python file operating-system