在 Python 2.7 中我得到以下结果:
>>> with open("README.md", "r") as fin:
... print(isinstance(fin, file))
...
True
在 python 3.5 中我得到:
>>> with open("README.md", "r") as fin:
... print(isinstance(fin, file))
...
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
NameError: name 'file' is not defined
所以,好吧,我查看了 Python 文档,发现在 Python 3.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
所以此时我很困惑。看着文档 https://docs.python.org/2/library/io.html#io.IOBase,我觉得Python 2.7应该报告True
.
显然我错过了一些基本的东西,也许是因为现在是美国东部时间下午 6:30,但我有两个相关的问题:
- 为什么Python会报错
False
for isinstance(fin, io.IOBase)
?
- 有没有办法测试变量是否是一个在 Python 2.7 和 3.5 中都可以工作的打开文件?