检查文件是否可以用 Python 读取:try or if/else?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32073498/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Check if file is readable with Python: try or if/else?
提问by Bram Vanroy
I have the following code:
我有以下代码:
import glob, os
for file in glob.glob("\*.txt"):
if os.access(file, os.R_OK):
# Do something
else:
if not os.access(file, os.R_OK):
print(file, "is not readable")
else:
print("Something went wrong with file/dir", file)
break
But I'm not entirely sure if this the right way to do it. Is it better to use try
and catch
the error? If so, how do I tryfor readability? Note the break
in my else statement. As soon as a file can't be read I want to abort the loop.
但我不完全确定这是否是正确的方法。使用try
和catch
错误更好吗?如果是这样,我如何尝试提高可读性?请注意break
我的 else 语句中的 。一旦无法读取文件,我想中止循环。
采纳答案by Rob?
For me, using a try-except at the same scope as one would use an if-else gains no readability. The value of exceptions is that they can be caught at a higher level in the call tree.
对我来说,在与使用 if-else 相同的范围内使用 try-except 没有可读性。异常的价值在于它们可以在调用树中的更高级别被捕获。
Moving out just one level, we avoid the break
statement:
仅移出一层,我们避免使用以下break
语句:
import glob, os
try:
for file in glob.glob("\*.txt"):
with open(file) as fp:
# do something with file
except IOError:
print("could not read", file)
But the true genius of exceptions is when the code simply disappears:
但真正的异常天才在于代码完全消失时:
# Operate on several files
# SUCCESS: Returns None
# FAIL: Raises exception
def do_some_files():
for file in glob.glob("\*.txt"):
with open(file) as fp:
# do something with file
Now it is the calling program's responsibility to display a useful error message on failure. We have removed responsibility for dealing with failure completely out of this code and into a whole other realm.
现在,调用程序有责任在失败时显示有用的错误消息。我们已经将处理失败的责任完全从这段代码中移除,转移到了另一个领域。
In fact, one can move the responsibility completely out of our program and into the interpreter. In that case, the interpreter will print some useful error message and terminate our program. If Python's default message is good enough for your users, I recommend not checking for errors at all. Thus, your original script becomes:
事实上,可以将责任完全从我们的程序中转移到解释器中。在这种情况下,解释器将打印一些有用的错误消息并终止我们的程序。如果Python的默认消息是配不上你的用户,我建议不要检查错误可言。因此,您的原始脚本变为:
import glob, os
for file in glob.glob("\*.txt"):
# Do something
回答by user126885
try:
# check to see if file is readable
with open(filename) as tempFile:
except Exception as e:
print e
# here you can modify the error message to your liking
This is usually what I do. It is robust and straight forward
这通常是我所做的。它坚固而直接
回答by bereal
In Python culture, it's more common to ask forgiveness, not permission, so it's preferable to catch the exception:
在 Python 文化中,请求宽恕而不是许可更为常见,因此最好捕获异常:
for filename in glob.glob('*.txt'):
try:
with open(filename) as fp:
# work with the file
except IOError as err:
print "Error reading the file {0}: {1}".format(filename, err)
break
That way you will also avoid any double-checks or race conditions.
这样,您还将避免任何双重检查或竞争条件。
回答by Tagar
More explicit way to check if file
is actually a file and not directory for example, and it is readable:
file
例如,检查是否实际上是文件而不是目录的更明确的方法,并且它是可读的:
from os import access, R_OK
from os.path import isfile
file = "/some/path/to/file"
assert isfile(file) and access(file, R_OK), \
"File {} doesn't exist or isn't readable".format(file)