如何检查对象是否是"文件"的实例?

the*_*tor 3 python python-3.x

曾经在Python(2.6)中可以问:

isinstance(f, file)
Run Code Online (Sandbox Code Playgroud)

但是在Python 3.0中file被删除了.

现在检查变量是否为文件的正确方法是什么?What'sNew文档没有提到这个......

aar*_*ing 5

def read_a_file(f)
    try:
        contents = f.read()
    except AttributeError:
        # f is not a file
Run Code Online (Sandbox Code Playgroud)

替换您计划使用的任何方法read.如果您希望在超过98%的时间内传递像对象这样的文件,那么这是最佳选择.如果您希望在超过2%的时间内传递非对象文件,那么正确的做法是:

def read_a_file(f):
    if hasattr(f, 'read'):
        contents = f.read()
    else:
        # f is not a file
Run Code Online (Sandbox Code Playgroud)

这正是你,你会怎样可以使用一个file类来测试对抗.(还有FWIW,我也有file2.6)请注意,此代码也适用于3.x.

  • @标记.你不应该在python中检查任何类型.我通常会在没有其他原因的情况下提出建议.您应该使用我为您的所有类型检查需求提供的两种方法之一. (2认同)

小智 5

在 python3 中,您可以引用io而不是file并写入

import io
isinstance(f, io.IOBase)
Run Code Online (Sandbox Code Playgroud)