isinstance文件python 2.7和3.5

2024-04-25 16:58:33 发布

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

在Python 2.7中,我得到了以下结果:

>>> with open("README.md", "r") as fin:
...     print(isinstance(fin, file))
... 
True

在python3.5中,我得到:

^{pr2}$

所以,我查看Python文档,发现在python3.5中,文件的类型是io.IOBase(或某些子类)。让我知道:

>>> import io
>>> with open("README.md", "r") as fin:
...     print(isinstance(fin, io.IOBase))
... 
True

但当我尝试使用Python 2.7时:

>>> import io
>>> with open("README.md", "r") as fin:
...     print(isinstance(fin, io.IOBase))
... 
False

我现在很困惑。看看documentation,我觉得Python2.7应该报告True。在

很明显我遗漏了一些基本的东西,也许是因为现在是东部时间下午6:30,但是我有两个相关的问题:

  1. 为什么Python为isinstance(fin, io.IOBase)报告False?在
  2. 有没有一种方法可以测试一个变量是一个在python2.7和3.5中都能工作的打开文件吗?在

Tags: 文件ioimportfalsetrueas报告with
2条回答

从链接的文档:

Under Python 2.x, this is proposed as an alternative to the built-in file object

所以它们在python2.x中是不一样的

至于第二部分,这在《Python2》和《Python3》中都很管用,虽然不是世界上最漂亮的东西:

import io
try:
    file_types = (file, io.IOBase)

except NameError:
    file_types = (io.IOBase,)

with open("README.md", "r") as fin:
    print(isinstance(fin, file_types))

对于Python2

import types
f = open('test.txt', 'r')   # assuming this file exists
print (isinstance(f,types.FileType))

对于Python3

^{pr2}$

(编辑:我以前的解决方案测试io.TextIOWrapper,它只适用于以文本模式打开的文件。请参见描述python3类层次结构的https://docs.python.org/3/library/io.html#class-hierarchy)。在

相关问题 更多 >