我不太确定这里发生了什么。根据Python的解释:
> os.W_OK: mode参数的值之一,用于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)我是否具有写入权限。
wx
,则允许在其中创建文件)。 - jfs