在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
所以在这一点上,我很困惑。看看documentation,我觉得Python 2.7应该报告True
。
显然我错过了一些基本的东西,也许是因为它是东部时间下午6:30,但我有两个相关的问题:
False
报告isinstance(fin, io.IOBase)
?答案 0 :(得分:4)
来自链接文档:
在Python 2.x中,建议将其作为内置文件对象的替代方法
所以它们在python 2.x中不一样。
至于第2部分,这适用于python2和3,虽然不是世界上最漂亮的东西:
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))
答案 1 :(得分:1)
对于python2
import types
f = open('test.txt', 'r') # assuming this file exists
print (isinstance(f,types.FileType))
对于python3
import io
import types
f1 = open('test.txt', 'r') # assuming this file exists
f2 = open('test.txt', 'rb') # assuming this file exists
print (isinstance(f1,io.IOBase))
print (isinstance(f2,io.IOBase))
(编辑:我以前的解决方案是针对io.TextIOWrapper测试的,它只适用于在文本模式下打开的文件。请参阅描述python3类层次结构的https://docs.python.org/3/library/io.html#class-hierarchy。