检查python中文件的权限

我正在尝试检查给定指定路径的文件的可读性.这就是我所拥有的:

def read_permissions(filepath):
    '''Checks the read permissions of the specified file'''
    try:
        os.access(filepath, os.R_OK) # Find the permissions using os.access
    except IOError:
        return False

    return True

这可以在运行时作为输出返回True或False.但是,我希望errno的错误消息随之而来.这就是我认为我必须做的事情(但我知道有些不对劲):

def read_permissions(filepath):
    '''Checks the read permissions of the specified file'''
    try:
        os.access(filepath, os.R_OK) # Find the permissions using os.access
    except IOError as e:
        print(os.strerror(e)) # Print the error message from errno as a string

    print("File exists.")

但是,如果我输入一个不存在的文件,它会告诉我该文件存在.有人可以帮助我解决我做错了什么(以及我将来可以做些什么来远离这个问题)?我还没有看到有人使用os.access尝试这个.我也打开其他选项来测试文件的权限.有人可以帮助我在出现问题时如何提出相应的错误消息吗?

此外,这可能适用于我的其他函数(他们在检查其他东西时仍然使用os.access,例如使用os.F_OK存在文件和使用os.W_OK的文件的写权限).这是我试图模拟的那种事情的一个例子:

>>> read_permissions("located-in-restricted-directory.txt") # Because of a permission error (perhaps due to the directory)
[errno 13] Permission Denied
>>> read_permissions("does-not-exist.txt") # File does not exist
[errno 2] No such file or directory

通过向问题返回相应的错误消息,我试图模拟这种事情.我希望这有助于避免对我的问题产生任何混淆.

我应该指出,虽然我已经阅读了os.access文档,但我不打算稍后打开该文件.我只是想创建一个模块,其中一些组件将检查特定文件的权限.我有一个基线(我提到的第一段代码),它作为我的其余代码的决策者.在这里,我只是尝试再次编写它,但是以用户友好的方式(不只是True或只是False,而是完整的消息).由于IOError可以通过几种不同的方式(例如权限被拒绝或不存在的目录),我试图让我的模块识别并发布问题.我希望这有助于您帮助我确定任何可能的解决方案.

最佳答案 无论传递的模式参数如何,当文件不存在时,os.access都返回False.

这在the documentation for os.access中没有明确说明,但并不是非常令人震惊的行为;毕竟,如果文件不存在,则无法访问它.按照文档的建议检查the access(2) man page给出了另一条线索,即访问在各种条件下返回-1.无论如何,你可以像我一样做,并检查IDLE中的返回值:

>>> import os
>>> os.access('does_not_exist.txt', os.R_OK)
False

在Python中,通常不鼓励在尝试实际执行有用的事情之前检查类型等.这种哲学通常用初始主义EAFP来表达,它代表宽容而不是许可.如果再次参考文档,您会发现这在本案中特别相关:

Note: Using access() to check if a user is authorized to e.g. open a file before actually doing so using open() creates a security
hole, because the user might exploit the short time interval between
checking and opening the file to manipulate it. It’s preferable to use
07002 techniques. For example:

06001

is better written as:

06002

如果您有其他原因检查权限而不是在调用open()之前再次猜测用户,则可以查看How do I check whether a file exists using Python?以获取一些建议.请记住,如果你真的需要提出异常,你可以自己提出它;没必要去野外寻找一个.

Since the IOError can be brought up a couple different ways (such as
permission denied, or non-existent directory), I am trying to get my
module to identify and publish the issue.

这就是上面的第二种方法.看到:

>>> try:
...     open('file_no_existy.gif')
... except IOError as e:
...     pass
...
>>> e.args
(2, 'No such file or directory')
>>> try:
...     open('unreadable.txt')
... except IOError as e:
...     pass
...
>>> e.args
(13, 'Permission denied')
>>> e.args == (e.errno, e.strerror)
True

但是你需要选择一种方法或另一种方法.如果您要求宽恕,请在try-except块中执行操作(打开文件)并适当地处理后果.如果你成功了,那么你就知道你成功了,因为没有例外.

另一方面,如果您以此方式请求权限(又名LBYL,Look Before You Leap),您仍然不知道在实际执行之前是否可以成功打开文件.如果在检查其权限后文件被移动怎么办?如果您没有想到要检查的问题怎么办?

如果您仍想要求许可,请不要使用try-except;你没有做这件事,所以你不会抛出错误.相反,使用带有os.access调用的条件语句作为条件.

点赞