【发布时间】:2015-02-10 15:11:27
【问题描述】:
我正在尝试检查给定路径的文件的可读性。这是我所拥有的:
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 可以通过几种不同的方式提出(例如权限被拒绝或不存在的目录),我试图让我的模块识别和发布问题。我希望这可以帮助您帮助我确定任何可能的解决方案。
【问题讨论】:
-
在
else块之后的except块中尝试使用print("File exists.")。这就是你要找的那种行为吗? -
尝试使用
return而不是print。 -
我刚试过(意思是 AirThomas 的建议)。它给了我相同的输出,说文件存在但实际上不存在。我将
print("File exists.")放在else块中except块之后。另外,mc10,我只是用print替换了return,它似乎也没有做任何事情。
标签: python python-2.7 error-handling file-permissions