代码之家  ›  专栏  ›  技术社区  ›  Bram Vanroy

检查文件是否可以用Python读取:try或if/else?

  •  27
  • Bram Vanroy  · 技术社区  · 10 年前

    我有以下代码:

    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
    

    但我不完全确定这样做是否正确。使用更好吗 try catch 错误?如果是,我该怎么做 尝试 为了可读性?注意 break 在我的else语句中。一旦文件无法读取,我就想中止循环。

    4 回复  |  直到 10 年前
        1
  •  40
  •   Tagar    4 年前

    检查是否 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"
    
        2
  •  19
  •   Robᵩ    10 年前

    对我来说,在与使用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
    
        3
  •  9
  •   bereal    6 年前

    在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
    

    这样,您还可以避免任何双重检查或比赛条件。

        4
  •  1
  •   user126885    10 年前
    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
    

    这通常是我所做的。 它结实、笔直