python - 检查对象是否是 Python 2 和 3 中的文件

标签 python python-3.x python-2.7 compatibility

是否有一种 Python 2/3 兼容的方法来检查对象是否为文件?

我需要检查一个对象 filehandler 是否实际上是一个 file 对象。此代码需要在 Python 2 和 3 中运行。在 Python 2 中我可以做到

isinstance(filehandler, file)

但是file is not part of Python 3 , 所以这段代码在使用 Python 3 运行时会引发 NameError

根据 this answer , 在 Python 3 中 io.IOBase 应该被用来检查一个对象是否是一个文件,但是 Python 2 的 file 没有继承 io.IOBase,所以 isinstance(filehandler, io.IOBase) 将不起作用。

我想过做 isinstance(filehandler, (io.IOBase, file)),但是当我用 Python 3 运行它时仍然会出现 NameError

有没有办法同时兼容 Python 2.7 和 3?

最佳答案

我发现最常用的方法是检查 Python 3 中的 hasattr。因此,我添加了一个检查 Python 版本的检查,并根据此执行正确的功能。

import sys

def isFile(f):
    return isinstance(f,file) if sys.version_info[0] == 2 else hasattr(f, 'read')        

f = open("post.php","r")
print(isFile(f))
print(isFile(10))

或者,您可以使用 lambda,但我发现它的可读性较差。

isFile = lambda f:isinstance(f,file) if sys.version_info[0] == 2 else hasattr(f, 'read')   

关于python - 检查对象是否是 Python 2 和 3 中的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47518707/

相关文章:

python - 使用 Python 更正 matplotlib 中的 x 值

python - 创建带有按钮的弹出窗口

python - 使用 PYTHON 的替代安装来安装 node.js

Python time.ctime() 格式 : 0-padding or space-padding

python - NLP:文档 OCR 中单词的位置特征

python - 使用 Python 操作 CSV 中的数据,仅将其应用于第一个结果

Python deepcopy 使用的内存比需要的多

python-3.x - Shutil.make_archive 未压缩到正确的目的地

python - 如何使用ansible正确升级pip?

python - 使用函数导入 CSV 文件并重命名数据框名称 - python 3.6