使用Python检查文件是否可读:try还是if/else?

2024-03-28 12:23:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下代码:

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错误更好吗?如果是的话,我该如何试着阅读呢?注意else语句中的break。一旦文件无法读取,我就要中止循环。


Tags: 代码inimporttxtforifaccessos
3条回答

在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

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

更明确的方法检查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)

对我来说,使用try除了与使用if-else的范围相同之外,不会获得可读性。异常的价值在于可以在调用树的更高级别捕获它们。

只移到一个级别,我们就避免了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

相关问题 更多 >