使用 Python 检查文件是否可读:尝试或 if/else?

Check if file is readable with Python: try or if/else?

我有以下代码:

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

但我不完全确定这样做是否正确。使用trycatch 错误更好吗?如果是这样,我如何 try 提高可读性?请注意我的 else 语句中的 break 。一旦无法读取文件,我想中止循环。

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

我通常就是这样做的。 它坚固而直接

在Python文化中,ask forgiveness, not permission更常见,所以最好捕获异常:

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

这样你也可以避免任何双重检查或竞争条件。

对我来说,在与使用 if-else 相同的范围内使用 try-except 没有可读性。异常的价值在于它们可以在调用树的更高级别被捕获。

只移出一层,我们避免了 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)

但异常的真正天才在于代码完全消失:

# 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

现在调用程序有责任在失败时显示有用的错误消息。我们已将处理故障的责任完全从这段代码中移除,并转移到了另一个领域。

事实上,可以将责任完全从我们的程序中转移到解释器中。在这种情况下,解释器将打印一些有用的错误信息并终止我们的程序。如果 Python 的默认消息对您的用户来说足够好,我建议完全 不检查错误 。因此,您的原始脚本变为:

import glob, os
for file in glob.glob("\*.txt"):
    # Do something

一种更明确的方法来检查 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), \
       f"File {file} doesn't exist or isn't readable"