【问题标题】:Why a file is writtable but os.access( file, os.W_OK ) return false?为什么文件是可写的,但 os.access(file, os.W_OK) 返回 false?
【发布时间】: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


    【解决方案1】:

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

    一旦文件被创建(存在),那么access(W_OK) 可能会返回true,如果您可以修改它的内容

    【讨论】:

    • 是的,在我创建该文件后,os.access(file, W_OK) 返回 True。但是,是否可以在不实际写入文件的情况下检查文件是否可写,然后在 python 中捕获异常?
    • @user36624:直到你创建了文件;没有什么要检查的。正如我在回答中所说:您可以检查目录-是否允许您在其中创建文件(如果设置了wx;您可以在其中创建文件)。
    【解决方案2】:

    也许您使用 sudo 运行您的脚本(或在 Windows 上使用类似的东西)? 我在 linux 上有这个(我给了 chmod 400):

    >>> os.access(fn, os.W_OK)
    False
    >>> f = open(fn, 'w')
    Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
    IOError: [Errno 13] Permission denied: '/tmp/non-writable'
    

    【讨论】:

      【解决方案3】:

      最初的问题是如何检查写入文件的权限。但是,在 Python 中,如果可能,最好使用 try-except 块来尝试写入文件,而不是测试访问权限。原因在 Python.org 网站上的 os.access() 文档中给出:https://docs.python.org/3/library/os.html

      来自网站:

      注意:使用 access() 来检查用户是否被授权,例如之前打开一个文件 实际上,使用 open() 这样做会产生一个安全漏洞,因为用户可能会利用检查和打开文件之间的短时间间隔来操作它。最好使用 EAFP 技术。例如:

      if os.access("myfile", os.R_OK):
          with open("myfile") as fp:
              return fp.read()
      return "some default data"
      

      最好写成:

      try:
          fp = open("myfile")
      except PermissionError:
          return "some default data"
      else:
          with fp:
              return fp.read()
      

      注意:即使 access() 指示 I/O 操作会成功,I/O 操作也可能会失败,特别是对于网络文件系统上的操作,其权限语义可能超出通常的 POSIX 权限位模型。

      【讨论】:

        猜你喜欢
        • 2021-05-08
        • 2011-04-09
        • 1970-01-01
        • 2018-02-17
        • 1970-01-01
        • 1970-01-01
        • 2017-10-23
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多